高效地转换Pandas中的数据

2024-07-08 07:12:39 发布

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

使用pandas和python解决此问题的最佳方法是什么

我目前有一个熊猫数据框,格式相对不太好,例如:

        Country      Indicator  2000  2010
0   Afghanistan            foo     1   2.5
1   Afghanistan            bar     3   4.5
2   Afghanistan            zoo     5   6.5
3       Bolivia            foo     7   8.5
4       Bolivia            bar     9  10.5
5       Bolivia            zoo    11  12.5
6      Cameroon            foo     2   1.5
7      Cameroon            bar     4   3.5
8      Cameroon            zoo     6   5.5
9       Denmark            foo     8   7.5
10      Denmark            bar    10   9.5
11      Denmark            zoo    12  11.5

假设我想为每一年将其分为两个独立的数据帧

2000年:

   foo bar zoo
0   1   3   5
1   7   9   11
2   2   4   6
3   8   10  12

2010年:

    foo  bar   zoo
0   2.5  4.5   6.5
1   8.5  10.5  12.5
2   1.5  3.5   5.5
3   7.5  9.5   11.5

在熊猫身上实现这一点最有效的方法是什么

提前谢谢


Tags: 数据方法pandasfoo格式barcountryindicator
1条回答
网友
1楼 · 发布于 2024-07-08 07:12:39

这种转变被称为“旋转”,有时也被称为“铸造”或“未熔化”。非常普遍的是it's covered by specific functions in the api.

df_years = df.pivot(index='Country', columns='Indicator', values=['2000', '2010'])    

            2000             2010           
Indicator    bar  foo   zoo   bar  foo   zoo
Country                                     
Afghanistan  3.0  1.0   5.0   4.5  2.5   6.5
Bolivia      9.0  7.0  11.0  10.5  8.5  12.5
...

这将导致multi level columns

df_years['2000']                                                                                                                                                                                    

Indicator    bar  foo   zoo
Country                    
Afghanistan  3.0  1.0   5.0
Bolivia      9.0  7.0  11.0
...
df_years['2010']                                                                                                                                                                                   

Indicator     bar  foo   zoo
Country                     
Afghanistan   4.5  2.5   6.5
Bolivia      10.5  8.5  12.5
...

您应该只使用这些数据帧,但如果您想要平面数据帧,可以这样分配:

df_2000 = df_years['2000']

Indicator    bar  foo   zoo
Country                    
Afghanistan  3.0  1.0   5.0
Bolivia      9.0  7.0  11.0
...

相关问题 更多 >

    热门问题