将列表列表堆叠到pandas数据框中[重复] - python

This question already has answers here:

Split (explode) pandas dataframe string entry to separate rows

(20个答案)

2年前关闭。

说我有以下数据框:

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参考方案

首先将split用于正则表达式的list-将,\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

Python:检查新文件是否在文件夹中[重复] - python

This question already has answers here: How do I watch a file for changes? (23个答案) 3年前关闭。 我是python的新手,但是我尝试创建一个自动化过程,其中我的代码将侦听目录中的新文件条目。例如,某人可以手动将zip文件复制到一个特定的文件夹中,并且我希望我的代码能够在文件完全…

如何根据子列表的长度对列表列表进行排序[重复] - python

This question already has answers here: Sorting Python list based on the length of the string (7个答案) 5年前关闭。 我有以下清单a = [['a', 'b', 'c'], ['d'…

为随机选择的变量分配一个值[重复] - python

This question already has answers here: How do I randomly select a variable from a list, and then modify it in python?                                                              …

从文件中读取用户名和密码[重复] - python

This question already has answers here: How to read a file line-by-line into a list? (28个答案) 2年前关闭。 如何在Python中逐行读取文本(例如用户名和密码)?例如,我可以在shell / bash中实现此目的:#!/bin/bash AUTH='/aut…

python切片的奇怪行为[重复] - python

This question already has answers here: Reversing a list slice in python (2个答案) 7个月前关闭。 假设我们有以下列表:>>> a = [x for x in range(10)] >>> print(a) [0, 1, 2, 3, 4, 5, 6…