我有必要清理一个大熊猫据帧,其中有一些需要一些数据被删除或剥离几列。为了使一个更干净的代码,我试图创建一个功能,可以做一些清洁和只与剥离的信息,我需要返回一个新列。
如可以在下面的代码中可以看出,我试图重写以不同的方式(也使用lambda函数)的代码,但不幸的是我没有发现任何财富。我总是得到错误'str' object has no attribute 'str'
import pandas as pd
def cleaner(x):
x = str(x)
x = x.str.split('/').str[1]
return x
data = ["First/A", "Second/B", "Third/C"]
dataframe = pd.DataFrame(data)
dataframe.columns = ["Source"]
dataframe["Destination"] = dataframe["Source"].apply(cleaner)
我很期待与只有“A”来获得一个新的列(目标),“B”,“C”值。
没有必要指定.str
可变x
,因为它是一个字符串对象。
def cleaner(x):
x = str(x)
#x = x.str.split('/').str[1]
x = x.split('/')[1]
return x
dataframe["Destination"] = dataframe["Source"].apply(cleaner)
此外,这种可以容易地降低到
dataframe["Destination"] = dataframe["Source"].str.split('/').str[1]
尝试这个:
import pandas as pd
def cleaner(x):
x = x.split('/')[1]
return x
data = ["First/A", "Second/B", "Third/C"]
dataframe = pd.DataFrame(data)
dataframe.columns = ["Source"]
dataframe["Destination"] = dataframe.apply(lambda x: cleaner(x['Source']), axis=1)