我有一个包含这样列的数据框 -
Name Id 2019col1 2019col2 2019col3 2020col1 2020col2 2020col3 2021col1 2021Ccol2 2021Ccol3
也就是说,每一年都会重复这些列。 我想取出年份并将其设为一列,以便最终数据框看起来像 -
Name Id Year col1 col2 col3
pandas 有没有办法实现这样的目标?
最佳答案
使用 wide_to_long
,但在列表理解中更改顺序年份到列名的结尾,例如 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
关于python - Pandas 将列转换为行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58517265/