繁体   English   中英

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

[英]Moving rows to columns through loops (pandas, 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  

您可以将年份代码“旋转”到列中,如下所示:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM