首页 > 解决方案 > 从一个创建多个数据框

问题描述

我有一个这样的数据框:

name   time    session1    session2    session3
Alex   135      10             3           5
Lee    136       2             6           4

我想根据每个会话制作多个数据框。例如,我想制作一个具有nametime和. 的数据框session1。并且数据框 2 具有nametimesession2。并且数据框 3 具有nametimesession3。我想使用 for 循环或任何其他方式更好,但不知道如何一次选择第 1、2、3 列,但不知道如何选择第 1、2、4 列等。任何人都知道这一点。数据保存在熊猫数据框中。我只是不知道如何在 Stackoverflow 中输入它。谢谢

标签: pythonpython-3.xpandasdataframe

解决方案


将其组织成数据框字典:

dict_of_dfs = {f'df {i}':df[['name','time', i]] for i in df.columns[2:]}

然后,您可以像访问任何其他字典值一样访问每个数据框:

>>> dict_of_dfs['df session1']
   name  time  session1
0  Alex   135        10
1   Lee   136         2
>>> dict_of_dfs['df session2']
   name  time  session2
0  Alex   135         3
1   Lee   136         6

推荐阅读