Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/314.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将列转换为行_Python_Pandas - Fatal编程技术网

Python 将列转换为行

Python 将列转换为行,python,pandas,Python,Pandas,我有一个包含如下列的数据框- Name Id 2019col1 2019col2 2019col3 2020col1 2020col2 2020col3 2021col1 2021Ccol2 2021Ccol3 也就是说,每年都会重复这些列。 我想把这一年去掉,把它做成一列,这样最终的数据框看起来像- Name Id Year col1 col2 col3 熊猫有没有办法做到这一点?使用,但在更改订单年份之前,列表中的列名称如2019col1到col12019结束: print (df)

我有一个包含如下列的数据框-

Name Id 2019col1 2019col2 2019col3 2020col1 2020col2 2020col3 2021col1 2021Ccol2 2021Ccol3
也就是说,每年都会重复这些列。 我想把这一年去掉,把它做成一列,这样最终的数据框看起来像-

 Name Id Year col1 col2 col3
熊猫有没有办法做到这一点?

使用,但在更改订单年份之前,列表中的列名称如2019col1到col12019结束:

print (df)
  Name   Id  2019col1  2019col2  2019col3  2020col1  2020col2  2020col3  \
0    a  456         4         5         6         2         3         4   

   2021col1  2021col2  2021col3  
0         5         2         1  

df.columns = [x[4:] + x[:4] if x[:4].isnumeric() else x for x in df.columns]

df = (pd.wide_to_long(df.reset_index(), 
                      ['col1','col2', 'col3'],
                      i='index',
                      j='Year').reset_index(level=0, drop=True).reset_index())
print (df)

   Year   Id Name  col1  col2  col3
0  2019  456    a     4     5     6
1  2020  456    a     2     3     4
2  2021  456    a     5     2     1
使用,但在变更单年份之前,使用列表中的列名称(如2019col1至col12019):

print (df)
  Name   Id  2019col1  2019col2  2019col3  2020col1  2020col2  2020col3  \
0    a  456         4         5         6         2         3         4   

   2021col1  2021col2  2021col3  
0         5         2         1  

df.columns = [x[4:] + x[:4] if x[:4].isnumeric() else x for x in df.columns]

df = (pd.wide_to_long(df.reset_index(), 
                      ['col1','col2', 'col3'],
                      i='index',
                      j='Year').reset_index(level=0, drop=True).reset_index())
print (df)

   Year   Id Name  col1  col2  col3
0  2019  456    a     4     5     6
1  2020  456    a     2     3     4
2  2021  456    a     5     2     1