在循环Pandas中使用数据帧名称

2024-09-30 03:24:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我有几个数据帧,需要对它们做同样的事情。在

我正在做这个:

df1=df1.reindex(newindex)
df2=df2.reindex(newindex)
df3=df3.reindex(newindex)
df4=df4.reindex(newindex)

有没有更简洁的方法?在

也许是像

^{pr2}$

Tags: 数据方法事情df1df2pr2df3df4
2条回答

是的,您的解决方案是好的,只需通过列表理解将其分配给新的list of DataFrame

dfs = [df1,df2,df3,df4]
dfs_new = [d.reindex(newindex) for d in dfs]

很好的解决方案,建议@Joe Halliwell,谢谢:

^{pr2}$

或者像suggest@roganjosh一样,可以创建数据帧字典:

^{3}$

然后按键选择每个数据帧:

print (dfs_new_dict['a'])

样本

df = pd.DataFrame({'a':[4,5,6]})
df1 = df * 10
df2 = df  + 10
df3 = df - 10
df4 = df / 10
dfs = [df1,df2,df3,df4]
print (dfs)
[    a
0  40
1  50
2  60,     a
0  14
1  15
2  16,    a
0 -6
1 -5
2 -4,      a
0  0.4
1  0.5
2  0.6]

newindex = [2,1,0]
df1, df2, df3, df4 = [d.reindex(newindex) for d in dfs]
print (df1)
print (df2)
print (df3)
print (df4)
    a
2  60
1  50
0  40
    a
2  16
1  15
0  14
   a
2 -4
1 -5
0 -6
     a
2  0.6
1  0.5
0  0.4

或者:

newindex = [2,1,0]
names = ['a','b','c','d']
dfs_new_dict = {name: d.reindex(newindex) for name, d in zip(names, dfs)}

print (dfs_new_dict['a'])
print (dfs_new_dict['b'])
print (dfs_new_dict['c'])
print (dfs_new_dict['d'])

如果有很多大数据帧,可以使用多个线程。我建议使用pathos模块(可以使用pip install pathos安装):

from pathos.multiprocessing import ThreadPool

# create a thread pool with the max number of threads
tPool = ThreadPool()

# apply the same function to each df
# the function applies to your list of dataframes
newDFs = tPool.map(lambda df: df.reindex(newIndex),dfs)

相关问题 更多 >

    热门问题