python - 将函数应用于 GroupBy pandas 数据框时出现 iterrows 错误
问题描述
我正在处理这样的熊猫数据框
ID have time
1 NaN 2010-07-01
1 1 2010-07-08
1 5 2011-07-08
1 NaN 2011-08-08
1 NaN 2012-05-08
1 NaN 2012-09-08
1 1 2012-10-08
2 NaN 2013-01-18
2 1 2013-02-18
2 NaN 2013-03-18
我想用ID组(个人)替换缺失值,并且只用一年内的个人级非缺失值替换记录:
ID have want time
1 NaN NaN 2010-07-01
1 1 1 2010-07-08
1 5 5 2011-07-08
1 NaN 5 2011-08-08
1 NaN 5 2012-05-08
1 NaN NaN 2012-09-08
1 1 1 2012-10-08
2 NaN NaN 2013-01-18
2 1 1 2013-02-18
2 NaN 1 2013-03-18
有没有一些有效的方法来完成这项工作?
我正在使用以下代码,它似乎适用于每一行
df = pd.DataFrame([
[1.0, np.nan, np.nan, "2010-07-01"],
[1.0,"1", "1", "2010-07-08"],
[1.0,"5", "5", "2011-07-08"],
[1.0,np.nan, "5", "2011-08-08"],
[1.0, np.nan, "5", "2012-05-08"],
[1.0, np.nan,np.nan, "2012-09-08"],
[1.0,"1", "1", "2012-10-08"],
[2.0, np.nan, np.nan, "2013-01-18"],
[2.0, "1", "1", "2013-02-18"],
[2.0, np.nan, "1", "2013-03-18"]
], columns = ['ID', 'have', 'want', 'time'])
df['time']=pd.to_datetime(df['time'], format='%Y-%m-%d')
def want(df):
for ind, row in df.iterrows():
df.loc[ind,'ewant']=df.loc[ind,'edatum']
if ind != 0:
if pd.isnull(df.loc[ind,'dosage']) == 1:
temp = ind - 1
df.loc[ind,'ewant']=df.loc[temp,'ewant']
else:
pass
else:
pass
df.loc[ind,'timespan']=(df.loc[ind,'edatum'] - df.loc[ind,'ewant']).days
df.loc[ind,'impu']=np.where( 0< (df.loc[ind,'edatum'] - df.loc[ind,'ewant']).days <= 365 , 1, 0)
return df
want(df)
但是当我尝试在“ID”组级别应用它时
want(df.groupby(['ID']))
我得到了这个迭代错误:
AttributeError: Cannot access callable attribute 'iterrows' of 'DataFrameGroupBy' objects, try using the 'apply' method
有没有办法解决这个 iterrows 错误?谢谢!
解决方案
这是完美的修复merge_asof
df1=df.dropna()
df=pd.merge_asof(df,df1,by='ID',on='time',tolerance=pd.Timedelta(12, unit='M'))
df#have_y is the column you want
ID have_x time have_y
0 1 NaN 2010-07-01 NaN
1 1 1.0 2010-07-08 1.0
2 1 5.0 2011-07-08 5.0
3 1 NaN 2011-08-08 5.0
4 1 NaN 2012-05-08 5.0
5 1 NaN 2012-09-08 NaN
6 1 1.0 2012-10-08 1.0
7 2 NaN 2013-01-18 NaN
8 2 1.0 2013-02-18 1.0
9 2 NaN 2013-03-18 1.0
推荐阅读
- sql - 计算平衡体积的窗口函数
- symfony - 无法使用多个提供商和防火墙注销 Symfony 5
- selenium - 无法通过 xpath 索引(硒)获取元素
- javascript - 方法 map() - 一次从后端数组获取所有对象值
- user-interface - 我的 Oculus 耳机干扰了我的 UI 滚动。我的光线交互器可以工作,但头显的移动也可以控制滚动
- google-apps-script - OnSelectionChange 与 SpreadsheetApp.getUI().alert("Message") 不一致 - Google Apps 脚本
- dataframe - 如何将内联数据集(增量)的参数化链接服务的参数传递给数据流?
- bash - 如何在 CMake 生成的 Makefile 中编译所有目标的子集,这些目标以 bash for 循环中的给定前缀开头
- node.js - 创建与 MongoDB 日期一起使用的自定义 GraphQLDateTime 标量
- reactjs - 用不同的值在 Mongoose 中更新多个文档——Express Js