通过循环将行移动到列(Pandas、python)

2024-05-20 15:46:02 发布

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

我想将年份代码移动到列中,然后将相应的人口移动到列中的行中。我想我已经迈出了第一步,但在我下面列出的步骤之后,我迷失了方向

for index, row in df.iterrows():
    cities = row['City']
    year = row['Year_code']
    
    df.loc[index, "2010"] = df['Population'][0]
    print(df)



      Year_code  Population                     City State   area    2010
0              1      115848      Ames, IA Metro Area  None  11180  115848
1              2      115850      Ames, IA Metro Area  None  11180  
2              3      115925      Ames, IA Metro Area  None  11180  
3              4      117424      Ames, IA Metro Area  None  11180  
4              5      118139      Ames, IA Metro Area  None  11180  

Tags: nonecitydfindex步骤codeareayear
1条回答
网友
1楼 · 发布于 2024-05-20 15:46:02

您可以将年份代码“透视”到如下列中:

pivot = df.pivot(index=['City', 'State', 'Area'], columns='Year_code', values='Population')

如果你想回到常规的0,1,2。。。索引,您可以使用 pivot = pivot.reset_index()

相关问题 更多 >