【问题标题】:pandas: reshape multiple column features in related rows熊猫:重塑相关行中的多列特征
【发布时间】:2021-11-16 22:22:52
【问题描述】:

我有一个数据集,其中 n 列带有标识数据,x 列带有属性。 我希望每一行都有标识符并且只有一个属性。如果一个对象有多个属性,它将出现在多行中。我可以用什么?谢谢

在 df 中

artist_name, country, album,song title...., extra artist 1, extra artist 2, extra artist 3,...extra artist 100

输出df

artist_name, country, album,song title...., extra artist 1  
artist_name, country, album,song title...., extra artist 2  
artist_name, country, album,song title...., extra artist 3  
...
artist_name, country, album,song title...., extra artist 100  

【问题讨论】:

标签: python pandas dataframe reshape


【解决方案1】:

我想你正在寻找df.melt()

https://pandas.pydata.org/docs/reference/api/pandas.melt.html

df = pd.DataFrame({'A': {0: 'a', 1: 'b', 2: 'c'},
                       'B': {0: 1, 1: 3, 2: 5},
                       'C': {0: 2, 1: 4, 2: 6}})

pd.melt(df, id_vars=['A'], value_vars=['B', 'C'])

【讨论】:

  • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
  • OP的问题确实缺乏信息,最好不要猜测。
猜你喜欢
  • 2016-10-29
  • 2013-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多