pandas 在第2部分中修改DataFrames [英] Pandas Modify DataFrames in Loop Part 2

查看:72
本文介绍了 pandas 在第2部分中修改DataFrames的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出以下数据帧:

import pandas as pd
k=pd.DataFrame({'A':[1,1],'B':[3,4]})
e=pd.DataFrame({'A':[1,1],'B':[6,7]})
k
    A   B
0   1   3
1   1   4

e
    A   B
0   1   6
1   1   7

我想在循环中应用分组和,但是这样做似乎并没有修改数据帧.

I'd like to apply a group-by sum in a loop, but doing so does not seem to modify the data frames.

这是我尝试过的:

for d in dfsout:
    d=d.groupby(d.columns[0]).apply(sum)
    print(d)

当我在循环中打印d时,表明正在执行正确的操作...

When I print d in the loop, it shows that the correct operation is occurring...

   A  B
A      
1  2  7
   A   B
A       
1  2  13

...但是当我打印数据帧k和e时,它们没有被修改.

...but then when I print data frames k and e, they have not been modified.

k
    A   B
0   1   3
1   1   4

e
    A   B
0   1   6
1   1   7

更新

我还尝试将其用作函数(可以循环工作,但仍不会修改):

I also tried using it as a function (works in loop, still does not modify):

def moddf(d):
    return d.groupby(d.columns[0]).apply(sum)
for d in dfsout:
    d=moddf(d)
    print(d)

提前谢谢!

推荐答案

好,您可以尝试

import pandas as pd
k=pd.DataFrame({'A':[1,1],'B':[3,4]})
e=pd.DataFrame({'A':[1,1],'B':[6,7]})
fields=['k','e']
dfsout=[k,e]
variables = locals()
for d,name in zip(dfsout,fields):
    variables["{0}".format(name)]=d.groupby(d.columns[0]).apply(sum)


k
Out[756]: 
   A  B
A      
1  2  7
e
Out[757]: 
   A   B
A       
1  2  13

这篇关于 pandas 在第2部分中修改DataFrames的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆