【问题标题】:unstacking a list of lists into a pandas dataframe [duplicate]将列表列表拆分为熊猫数据框[重复]
【发布时间】:2018-07-26 08:20:35
【问题描述】:

假设我有以下数据框:

x = pd.DataFrame({'a':['x, y', 'x, t, x, r', 'y, t'],
          'b':[1, 0, 1]})

            a  b
0        x, y  1
1  x, t, x, r  0
2        y, t  1

我想去

  letter  num
0      x    1
1      y    1
2      x    0
3      t    0
4      x    0
5      r    0
6      y    1
7      t    1

我已经通过以下方式解决了这个问题,但我觉得我让它变得比它需要的更复杂。

x.a = x.a.str.split(",")

empty = []
for b, a in zip(x.b, x.a):
    empty.append([b] * len(a))

t = [item for sublist in empty for item in sublist]
y = [item for sublist in x.a for item in sublist]

pd.DataFrame({'letter':t, 'num':y})

   letter num
0       1   x
1       1   y
2       0   x
3       0   t
4       0   x
5       0   r
6       1   y
7       1   t

有没有更好的方法来解决这个问题?

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    split 用于lists,首先通过正则表达式-,\s+ 用于带有一个或多个空格的逗号,然后numpy.repeat 通过numpy.concatenate 进行展平,最后使用DataFrame 构造函数:

    a = x.a.str.split(",\s+")
    b = np.repeat(x.b.values, a.str.len())
    c = np.concatenate(a.values)
    
    df = pd.DataFrame({'letter':c, 'num':b})
    print (df)
      letter  num
    0      x    1
    1      y    1
    2      x    0
    3      t    0
    4      x    0
    5      r    0
    6      y    1
    7      t    1
    

    【讨论】:

      【解决方案2】:

      让我们将每一行扩展一加上'a' 列中的逗号数。然后用新值覆盖列'a'

      x.loc[
          x.index.repeat(x.a.str.count(', ') + 1)
      ].assign(
          a=', '.join(x.a).split(', ')
      ).rename(columns=dict(a='letter', b='num'))
      
        letter  num
      0      x    1
      0      y    1
      1      x    0
      1      t    0
      1      x    0
      1      r    0
      2      y    1
      2      t    1
      

      【讨论】:

        【解决方案3】:

        只是找到一种新的方式:-)

        x.set_index('b').a.str.get_dummies(sep=',').replace(0,np.nan).stack().reset_index().drop(0,1)
        Out[481]: 
           b level_1
        0  1       y
        1  1       x
        2  0       r
        3  0       t
        4  0       x
        5  0       x
        6  1       t
        7  1       y
        

        【讨论】:

          猜你喜欢
          • 2019-12-28
          • 1970-01-01
          • 2019-09-30
          • 2018-10-17
          • 2018-12-04
          • 1970-01-01
          • 2020-08-13
          • 1970-01-01
          • 2021-02-26
          相关资源
          最近更新 更多