[英]Is there a way to convert a time-series of rows (same feature, 5 rows [1 for each year]) into a single feature with 20 columns using Pandas?
全部。 很抱歉,这与其他问题相似,但我找不到与我的特定情况相匹配的好答案。
我正在处理时间序列的图像数据。 我的 dataframe 中的每个功能都有五行数据:每年 1 行。 我想将这五行转换为列,以便每个功能只有一行,但我不能丢失或聚合任何数据。
我的 dataframe 看起来像这样:
df = pd.DataFrame([[1, 3, 4, 9, 31, 2016],
[1, 23, 12, 47, 3 , 2017],
[1, 5, 7, 13, 48, 2018],
[1, 16, 11, 6, 39, 2019],
[1, 12, 2, 53, 26, 2020]], columns=['ID' , 'r-val' , 'b-val' , 'g-val' , 'ndvi' , 'year'])
ID | r-val | b-val | g-val | ndvi | year
1 3 4 9 31 2016
1 23 12 47 3 2017
1 5 7 13 48 2018
1 16 11 6 39 2019
1 12 2 53 26 2020
我需要它看起来像这样:
ID | r-val_2016 | b-val_2016 | g-val_2016 | ndvi_2016 | r-val_2017 | b-val_2017 | g-val_2017 | ndvi_2017 | r-val_2018 | b-val_2018 | g-val_2018 | ndvi_2018 ... and so on.
1 3 4 9 31 23 12 47 3 5 7 13 48
我尝试过 concat、merge 和 groupby,但似乎无法获得所需形状的数据。 有没有人有什么建议?
使用pivot
df = df.pivot(index='ID', columns=['year'], )
df.columns = ['_'.join(map(str,i)) for i in df.columns.values]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.