熊猫在迭代数据帧的同时改变数据帧

问题描述:

我是熊猫的初学者。 用例是,我有一个包含实际数据的两个dataframes一个(比如DF1):熊猫在迭代数据帧的同时改变数据帧

teamID yearID W 1B PAR  2B PAR  3B PAR  HR PAR  BB PAR 
1366 LAA 1961 70 0.147748 0.035708 0.003604 0.030958 0.111548 
1367 KC1 1961 61 0.164751 0.035982 0.007829 0.014993 0.096618 
1377 NYA 1962 96 0.167148 0.038536 0.004656 0.031952 0.093770 
1379 LAA 1962 86 0.159482 0.038027 0.005737 0.022455 0.098672 
1381 CHA 1962 85 0.165797 0.040756 0.009129 0.014998 0.101076 

我需要平均中心每年的数据。要实现,我已经创建使用以下命令独立的机架,每年平均有(说DF2)

df2 = df1.groupby('yearID').mean() 
df2 = df1.reset_index() #not mandatory in this case! 
df2.head() 

    yearID W   1B PAR  2B PAR  3B PAR  HR PAR BB PAR 
0 1961 65.500000 0.156249 0.035845 0.005717 0.022975 0.104083 
1 1962 78.454545 0.165632 0.035853 0.006777 0.023811 0.088590 
2 1963 78.142857 0.162467 0.034020 0.006896 0.021254 0.080336 
3 1964 81.727273 0.167251 0.036336 0.006748 0.021548 0.079152 
4 1965 82.000000 0.160042 0.035539 0.006534 0.022693 0.085745 

现在,意味着中心DF1,我对循环之下运行:

for i, row in df1.iterrows(): 
    year = df2[df2['yearID']==row[1]] 
    row = row-year 
    print(row) 
df1.head() 

有趣,print(row)打印更新的列值,但最后,df1.head()按原样打印原始数据框。这是有道理的,因为当我们改变“行”变量时,我们实际上是在改变一个快照/实例而不是实际的数据帧的内容。

预期输出:列的每年平均1B PAR,PAR 2B BB .... PAR应该等于0。

Two questions : 
> How do I update my dataframe(df1 in above case) as well? 
> Is there a way to subtract just the subset of columns and not all of them? Current code is subtracting yearId as well but we'd want to center just (1B PAR:BB PAR) columns 

谢谢!


PS:我只是修改我的for循环,现在我收到了预期的效果:

for i, row in df1.iterrows(): 
    year = df2[df2['yearID']==row[1]] 
    row = row-year 
    df1.set_value(i,'1B PAR', row['1B PAR']) 
    df1.set_value(i,'2B PAR', row['2B PAR']) 
    df1.set_value(i,'3B PAR', row['3B PAR']) 
    df1.set_value(i,'HR PAR', row['HR PAR']) 
    df1.set_value(i,'BB PAR', row['BB PAR']) 
df1.head() 

    teamID yearID  W  1B PAR  2B PAR  3B PAR  HR PAR BB PAR 
1366 LAA 1961 70 -0.164751 -0.000137 -0.002113 0.007983 0.007465 
1367 KC1 1961 61 -0.147748 0.000137 0.002113 -0.007983 -0.007465 
1377 NYA 1962 96 -0.164116 0.002683 -0.002121 0.008141 0.005180 

有没有更好的实现相同的结果呢?我相信这不是完成任务的最美丽方式!

不同的方法:

msuf = '_mean' 
dfm = pd.merge(df1,df2,on="yearID",suffixes=('',msuf)) 
for column in ["1B PAR","2B PAR","3B PAR","HR PAR","BB PAR"]: 
    dfm[column] = dfm[column] - dfm[column+msuf] 
    dfm = dfm.drop(column+msuf,axis=1) 

首先,合并上yearID两个dataframes,然后做你的增减列明智和下降的均列。

+0

这看起来很酷,会测试一次。谢谢! – buch11

+0

如果能解决您的问题,请记住接受我的回答。 – Khris