【问题标题】:Transpose dataframe in Python pandas在 Python pandas 中转置数据帧
【发布时间】:2020-12-08 14:48:54
【问题描述】:

我有一个这样的数据框

输入

>>> df

 sent      cite 
 a         1,2,3
 b         2,4
 c         5

我想转置每行包含 cite 和 sent 组合的值的数据帧。请注意,citesent 可以重复(例如,cite 2

预期输出

>>> df

 cite      sent 
 1         a
 2         a
 2         b
 3         a
 4         b
 5         c

我试过了,但是没用

df = df.pivot( columns='cite', values='sent')

【问题讨论】:

  • 在 DataFrame 中保存值的 dtype 是什么?列表?

标签: python pandas dataframe pivot transpose


【解决方案1】:

Series.str.splitdf.explodedf.sort_values 一起使用:

In [141]: df = df.assign(cite=df['cite'].str.split(',')).explode('cite').sort_values('cite')

In [142]: df
Out[142]: 
  sent cite
0    a    1
0    a    2
1    b    2
0    a    3
1    b    4
2    c    5

【讨论】:

    【解决方案2】:

    尝试split 然后explode

    df = df.assign(cite=df['cite'].str.split(',')).explode('cite')
    

    【讨论】:

      猜你喜欢
      • 2019-06-01
      • 1970-01-01
      • 2018-08-14
      • 1970-01-01
      • 2016-10-17
      • 2016-01-03
      • 1970-01-01
      • 2017-02-04
      • 1970-01-01
      相关资源
      最近更新 更多