我从pandas.DataFrame.apply()中得到一个AttributeError。尽管如此,这个函数似乎还能工作,但我想更好地理解apply(),所以我还是把这个问题贴出来......
我有两个数据框,像这样。
a = pd.DataFrame(data = {
'ID': ['123', '456', '789'],
'TIME': [1.5, 2, 3]
})
b = pd.DataFrame(data = {
'ID': ['123', '456', '789'] * 2,
'TIME_START': [1, 3, 3, 2, 1, 5],
'TIME_END': [5, 4, 6, 6, 3, 6],
'CORR_KEY': ['abc', 'def', 'ghi', 'jkl', 'mno', 'pqr']
})
我把它们合并成这样
c = a.merge(b, how = 'inner', on = 'ID')
然后我得到以下结果:
print(c)
ID TIME TIME_START TIME_END CORR_KEY
0 123 1.5 1 5 abc
1 123 1.5 2 6 jkl
2 456 2.0 3 4 def
3 456 2.0 1 3 mno
4 789 3.0 3 6 ghi
5 789 3.0 5 6 pqr
现在我需要把记录放入 c 哪儿 TIME_START <= 时间 <= 时间_END 是FALSE。这样一来,我就会发现只有那些有相关的 CORR_KEY. (例如,正确的是 CORR_KEY 对于 身份证 123是abc,而不是jkl)。)
我使用下面的函数,并沿着数据帧应用它。
def drop_records(df):
start_condition = df['TIME_START'] <= df['TIME']
end_condition = df['TIME'] <= df['TIME_END']
df.drop(df[~(start_condition) | ~(end_condition)].index, inplace = True)
return df
c = c.apply(drop_records(c))
结果是:
AttributeError: 'ID' is not a valid function for 'Series'object
然而,检查 c 再次,我得到了预期的输出。
print(c)
ID TIME TIME_START TIME_END CORR_KEY
0 123 1.5 1 5 abc
3 456 2.0 1 3 mno
4 789 3.0 3 6 ghi
那么,是什么导致了AttributeError?
谢谢!我从pandas.DataFrame.apply()得到一个AttributeError。
当你做 apply
数据框被分成一系列,每列一列,函数被应用于serie。因为 ID
只是第一列。apply
正在尝试执行 drop_records(c)
但给他们送去的是 ID
这将导致 AttributeError
.
你不需要 apply
这里的一个函数,只是。
c = drop_records(c)
或者使用布尔掩码:
mask = (c.TIME_START <= c.TIME) & (c.TIME <= c.TIME_END)
c = c[mask]
或者像@Sandeep Kadapa所建议的那样进行查询.
你的解决方案太夸张了。你可以使用 query
以直接获得你的输出。
c = c.query('TIME_START <= TIME <= TIME_END')
print(c)
ID TIME TIME_START TIME_END CORR_KEY
0 123 1.5 1 5 abc
3 456 2.0 1 3 mno
4 789 3.0 3 6 ghi