Python 如何使用另一个已筛选的数据帧更新数据帧
我有两个数据帧。我需要用第二列中的平均值更新第一列中的一列,并按索引分组。 这里有一个例子 df1(col1是索引) df2(col1是索引) 我需要df2的col2(a=2,d=3)中的平均值,并且只为col3=X的行更新df1 我试过这个Python 如何使用另一个已筛选的数据帧更新数据帧,python,pandas,dataframe,pandas-groupby,Python,Pandas,Dataframe,Pandas Groupby,我有两个数据帧。我需要用第二列中的平均值更新第一列中的一列,并按索引分组。 这里有一个例子 df1(col1是索引) df2(col1是索引) 我需要df2的col2(a=2,d=3)中的平均值,并且只为col3=X的行更新df1 我试过这个 df1.loc[df1.col3=='X'].update(df2.groupby(df2.index),'col2'].mean().to_frame()) 只有在我不使用loc的情况下,它才有效 我想要的结果 df1(col1是索引) 使用:
df1.loc[df1.col3=='X'].update(df2.groupby(df2.index),'col2'].mean().to_frame())
只有在我不使用loc的情况下,它才有效
我想要的结果
df1(col1是索引)
使用:
col2 col3
col1
a 1 0
a 3 0
d 2 0
d 4 0
df1.loc[df1.col3=='X'].update(df2.groupby(df2.index),'col2'].mean().to_frame())
col2 col3
col1
a 2 X
b 0 0
c 0 0
d 0 0
m=df2.groupby(df2.index).col2.mean()
df1.loc[df1.col3=='X','col2']=m
print(df1)
col2 col3
col1
a 2 X
b 0 0
c 0 0
d 0 0