将列表列表堆叠到pandas数据框中 [英] unstacking a list of lists into a pandas dataframe

查看:56
本文介绍了将列表列表堆叠到pandas数据框中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有以下数据框:

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

我已经通过以下方式解决了这个问题,但是我觉得我正在使它变得比所需的更加复杂.

I have solved the issue the following way, but I feel like i'm making it more complicated than it needs to be.

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

是否有更好的方法来解决此问题?

Is there a better way to solve this problem?

推荐答案

使用 split 首先是由正则表达式表示的list-,\s+是带有一个或多个空格的逗号,然后是

Use split for lists first by regex - ,\s+ for comma with one or more spaces, and then numpy.repeat with flatenning by numpy.concatenate and last DataFrame constructor:

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

这篇关于将列表列表堆叠到pandas数据框中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆