python - 如何将具有值为列表的列的数据框转换为数据框,其中该列中每个列表的每个元素都成为新行

标签 python pandas

我有一个包含这种格式条目的数据框:

user_id,item_list
0,3569 6530 4416 5494 6404 6289 10227 5285 3601 3509 5553 14879 5951 4802 15104 5338 3604 2345 9048 8627
1,16148 8470 7671 8984 9795 6811 3851 3611 7662 5034 5301 6948 5840 345 14652 10729 8429 7295 4949 16144
...

*请注意,user_id 不是数据帧的索引

我想将数据框转换成如下所示:

user_id,item_id
0,3569
0,6530
0,4416 
0,5494 
...
1,4949
1,16144
...

现在我正在尝试这样做,但效率极低:

df = pd.read_csv("20recs.csv")
numberOfRows = 28107*20
df2 = pd.DataFrame(index=np.arange(0, numberOfRows),columns=('user', 'item'))
iter = 0
for index, row in df.iterrows():
    user = row['user_id']
    itemList = row['item_list']
    items = itemList.split(' ')
    for item in items:
        df2.loc[iter] = [user]+[item]
        iter = iter + 1

如您所见,我什至尝试为数据框预分配内存,但似乎没什么用。

所以一定有更好的方法来做到这一点。谁能帮帮我?

最佳答案

使用 split 将列表转换为实际列表,然后使用 explode 来......好吧,分解 DataFrame。 需要 pandas >= 0.25.0

>>> df = pd.DataFrame({'user_id': [0,1], 'item_list': ['1 2 3', '4 5 6']})
>>> df

   user_id item_list
0        0     1 2 3
1        1     4 5 6

>>> (df.assign(item_id=df.item_list.apply(lambda x: x.split(' ')))
       .explode('item_id')[['user_id', 'item_id']])

   user_id   item_id
0        0         1
0        0         2
0        0         3
1        1         4
1        1         5
1        1         6

关于python - 如何将具有值为列表的列的数据框转换为数据框,其中该列中每个列表的每个元素都成为新行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59128344/

相关文章:

python - 通过使用 Foo() 参数运行子命令,在主单击组命令上实例化 Foo() 类

python - 覆盖类的一个实例的 __getattr__ 方法?

python - Python 中的二进制 I/O

python - 在没有任何客户 ID 的情况下汇总客户支出

python - 在 Pandas 中创建类似 Excel 的 SUMIFS

python - 如何将 Pandas 数据框转换为带有列名的 numpy 数组

python - 在 pandas 数据框中非常复杂的条件下获取最大值和最小值

python:设置不同的配置文件进行单元测试

python - 如何在初始化变量的结构之间随机选择?

pandas - Python Pandas:从多级列索引中删除一列?