简体   繁体   English

如何将 pandas dataframe 多列转换为单列

[英]How to convert a pandas dataframe multicolumn to one single column

I am trying to convert a pandas dataframe with different columns per year, to a pandas dataframe with one column with the value and other column with the year: I am trying to convert a pandas dataframe with different columns per year, to a pandas dataframe with one column with the value and other column with the year:

input输入

column name: a, b, c, d
column 2015: 1, 2, 3, 4
column 2016: 5, 6, 7, 8

Desired output所需 output

column name: a, b, c, d, a, b, c, d
column year: 2015, 2015, 2015, 2015, 2016, 2016, 2016, 2016
column value: 1, 2, 3, 4, 5, 6, 7, 8

I've trying with a for loop and melt function but is not the ideal solution.我尝试使用 for 循环并融化 function 但不是理想的解决方案。

Thanks!谢谢!

pandas.melt would do the job. pandas.melt可以完成这项工作。

print(df)
###
  name  2015  2016
0    a     1     5
1    b     2     6
2    c     3     7
3    d     4     8
print(pd.melt(df, value_vars=['2015', '2016'], var_name='year', id_vars='name'))
###
  name  year  value
0    a  2015      1
1    b  2015      2
2    c  2015      3
3    d  2015      4
4    a  2016      5
5    b  2016      6
6    c  2016      7
7    d  2016      8

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

相关问题 Python Pandas:多列数据框-移一列而不更改另一列 - Python pandas: Multicolumn dataframe - Shift one column without changing the other 如何将单列数据框合并到多列数据框? - how can I merge single column dataframe to multicolumn dataframe? 如何将单列 Pandas DataFrame 转换为 Series - How to convert a single column Pandas DataFrame into Series 将元组列表转换为 pandas dataframe 的单列? - convert list of tuples into single column of pandas dataframe? Pandas数据框:将列转换为单列的行 - Pandas dataframe: convert columns into rows of a single column Python Pandas DataFrame 将每一行的列转换为单个列作为 Pandas 系列 - Python Pandas DataFrame convert columns of each row to one single column as Pandas Series Pandas DataFrame:如何将二进制列转换为一个分类列? - Pandas DataFrame: How to convert binary columns into one categorical column? 如何将一列的Pandas数据框转换为两列的Pandas数据框? - How do I convert a Pandas Dataframe with one column into a Pandas Dataframe of two columns? 如何将 Pandas 数据框转换为单个列表 - How to Convert Pandas Dataframe to Single List 如何基于Pandas中特定值的一列转换仅在一列中仅具有唯一值的DataFrame - How to convert a DataFrame that only has unique value in one column based on one column in specific value in Pandas
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM