Pandas for循环复制列以分隔数据帧,相应地重命名df

问题描述 投票:1回答:3

我正在尝试采用数据帧,从第2列开始迭代每个列,然后将第一个常量列+下一个列逐个复制到新数据帧。

df = pd.DataFrame({'Year':[2001 ,2002, 2003, 2004, 2005], 'a': [1,2, 3, 4, 5], 'b': [10,20, 30, 40, 50], 'c': [0.1, 0.2, 0.3, 0.4,0.5]})
df

要获得类似于此输出的结果,但我需要它循环,因为我可以有多达40列来运行逻辑。

df_a=pd.DataFrame()
df_a=df[['Year', 'a']].copy()
df_b=df[['Year', 'b']].copy()
df_c=df[['Year', 'c']].copy()
print(df_a)
print(df_b)
print(df_c)

如果我知道如何命名df _ ['列的名称正在复制']也会很好。非常感谢你,如果它是重复的话,我很抱歉。

python pandas loops dataframe
3个回答
2
投票

我建议通过词典理解来拆分它,然后你会得到一个单独数据帧的字典。例如:

dict_of_frames = {f'df_{col}':df[['Year', col]] for col in df.columns[1:]}

为您提供df_adf_bdf_c的字典,您可以像访问任何其他字典一样访问它:

>>> dict_of_frames['df_a']
   Year  a
0  2001  1
1  2002  2
2  2003  3
3  2004  4
4  2005  5

>>> dict_of_frames['df_b']
   Year   b
0  2001  10
1  2002  20
2  2003  30
3  2004  40
4  2005  50

1
投票

你需要制作一个像下面这样的数据帧字典,列名作为键,子数据帧作为值。

df = df.set_index('Year')
dict_ = {col: df[[col]].reset_index() for col in df.columns}

您只需使用列名访问字典并获取相应的数据帧即可。

dict_['a']

输出:

    Year    a
0   2001    1
1   2002    2
2   2003    3
3   2004    4
4   2005    5

你可以通过以下方式迭代dict_

for col, df in dict_.items():
    print("-"*40) #just for separation
    print(df) #or print(dict_[col])

输出:

----------------------------------------
   Year  a
0  2001  1
1  2002  2
2  2003  3
3  2004  4
4  2005  5
----------------------------------------
   Year   b
0  2001  10
1  2002  20
2  2003  30
3  2004  40
4  2005  50
----------------------------------------
   Year    c
0  2001  0.1
1  2002  0.2
2  2003  0.3
3  2004  0.4
4  2005  0.5

0
投票

您无需创建字典即可复制和访问所需的数据。您可以简单地复制数据帧(如果您有可变元素,则使用深层复制),然后使用索引来访问特定系列:

dfs = df.set_index('Year').copy()

print(dfs['a'])

Year
2001    1
2002    2
2003    3
2004    4
2005    5
Name: a, dtype: int64

您可以通过pd.DataFrame.iteritems遍历您的列:

for key, series in dfs.iteritems():
    print(key, series)

是的,这给出了系列,但它们可以通过series.reset_index()series.to_frame()轻松转换为数据帧。

© www.soinside.com 2019 - 2024. All rights reserved.