python - Pandas:宽格式列出的三个列

标签 python pandas dataframe

如何使用第一列的值作为其他列的标题来扩展一组列?

例如:

x = pd.DataFrame({'id':[11,998,3923], 'count':[7,7,7],
  'attributes':['VIS,TEMP,MIN','MIN,VIS,TEMP','MIN,VIS'],
  'attribute_values':['0,4,2','2,3,0','0,9'],
  'attribute_years':['2000,2001,2002','2001,2002,2003','2008,2009']})

(编辑:请注意,属性可能乱序或丢失。)

<表类=“s-表”> <标题> 索引 id 计数 属性 attribute_values attribute_years <正文> 0 11 7 可见光、温度、最低 0,4,2 2000,2001,2002 1 998 7 最低、可见光、温度 2,3,0 2001,2002,2003 2 3923 7 最小,可见度 0,9 2008,2009

在这种情况下,attributes列值应用于创建带有 attribute_values 的新列和attribute_years列。

理想输出:

<表类=“s-表”> <标题> 索引 id 计数 attribute_values_VIS attribute_values_TEMP attribute_values_MIN attribute_years_VIS attribute_years_TEMP attribute_years_MIN <正文> 0 11 7 0 4 2 2000 2001 2002 1 998 7 3 0 2 2002 2003 2001 2 3923 7 9 NaN 0 2009 NaN 2008

最佳答案

解决方案

将属性中的字符串拆分为分隔符 , 周围的列,以转换为列表,然后 explode 将列表转换为单独的行,然后 pivot使用 columns=attributes 进行 reshape ,最后使用 map + join 展平多索引

y = x.set_index(['id', 'count'])
y = y.apply(lambda s: s.str.split(',')).explode([*y])
y = y.pivot(columns='attributes')
y.columns = y.columns.map('_'.join)
y = y.reset_index()

>>> y
     id  count attribute_values_MIN attribute_values_TEMP attribute_values_VIS attribute_years_MIN attribute_years_TEMP attribute_years_VIS
0    11      7                    2                     4                    0                2002                 2001                2000
1   998      7                    2                     0                    3                2001                 2003                2002
2  3923      7                    0                   NaN                    9                2008                  NaN                2009

关于python - Pandas:宽格式列出的三个列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72306515/

相关文章:

python - 如何将色阶标签移动到 matplotlib/xarray 中彩色字段的中间?

python - 如何获取QGraphicsItem坐标系中的光标点击位置?

python - 在 Pandas 中获取带有向量的数据帧的点积,并返回数据帧

python - Pandas read_xml() 方法测试策略

python - Pandas 数据框 : Using the count function to filter data

python - 如何使用stockstats查看MACD信号?

python - Flask 自动转义具有不常见扩展名的文件

python - Pandas python中的并行处理

python - Pandas :重新采样多索引数据帧

python - 如何将具有平均百分比和平均计数的列添加到数据框?