如何在不指定数据框的列名的情况下在 python 中使用 `apply`?
How to use `apply` in python without specifying the column name of the data frame?
我正在尝试对数据框使用 apply
函数从日期列中删除字符串。例如,我下面有一个数据框,我想使用 dateutil
包从 Start
和 Finish
列中删除字符串,而不指定列名。
df=[["1/5/2020 Yes", "5/9/2020 String",2,6],["1/8/2020 No","5/8/2020 sponge",8,9],["8/9/2020 Spine","5/8/2020 spike",8,9]]
df=pd.DataFrame(df)
df.columns=["Start","Finish","x1","x2"]
这是我的试用版,但它无法正常工作并抛出 KeyError Traceback (most recent call last)
df[0] = df[0].apply(dparser.parse,fuzzy=True)
df[1] = df[1].apply(dparser.parse,fuzzy=True)
谁能帮我解决这个问题?
df[0]
访问 named 0
列,它不在您的数据框中。您想给出正确的名称,即 df['Start']
或使用 iloc
:df.iloc[:,0]
.
此外,另一种提取日期的方法是使用 regex
模式,例如:
for i in range(2):
df.iloc[:,i] = df.iloc[:,i].str.extract('^(\S+)')[0]
输出:
Start Finish x1 x2
0 1/5/2020 5/9/2020 2 6
1 1/8/2020 5/8/2020 8 9
2 8/9/2020 5/8/2020 8 9
我正在尝试对数据框使用 apply
函数从日期列中删除字符串。例如,我下面有一个数据框,我想使用 dateutil
包从 Start
和 Finish
列中删除字符串,而不指定列名。
df=[["1/5/2020 Yes", "5/9/2020 String",2,6],["1/8/2020 No","5/8/2020 sponge",8,9],["8/9/2020 Spine","5/8/2020 spike",8,9]]
df=pd.DataFrame(df)
df.columns=["Start","Finish","x1","x2"]
这是我的试用版,但它无法正常工作并抛出 KeyError Traceback (most recent call last)
df[0] = df[0].apply(dparser.parse,fuzzy=True)
df[1] = df[1].apply(dparser.parse,fuzzy=True)
谁能帮我解决这个问题?
df[0]
访问 named 0
列,它不在您的数据框中。您想给出正确的名称,即 df['Start']
或使用 iloc
:df.iloc[:,0]
.
此外,另一种提取日期的方法是使用 regex
模式,例如:
for i in range(2):
df.iloc[:,i] = df.iloc[:,i].str.extract('^(\S+)')[0]
输出:
Start Finish x1 x2
0 1/5/2020 5/9/2020 2 6
1 1/8/2020 5/8/2020 8 9
2 8/9/2020 5/8/2020 8 9