如何将由列表列表组成的pandas df列转换为字符串。 df中“类别”列的摘录
[['Electronics', 'Computers & Accessories', 'Cables & Accessories', 'Cables & Interconnects', 'USB Cables'], ['Video Games', 'Sony PSP']]
[['Video Games', 'PlayStation 3', 'Accessories', 'Controllers', 'Gamepads']]
[['Cell Phones & Accessories', 'Accessories', 'Chargers', 'Travel Chargers'], ['Video Games', 'Nintendo DS']]
我尝试了以下代码:
df.loc[:,"categories"]=[item for sublist in df.loc[:,"categories"] for item in sublist]
但是它给我一个错误。还有其他方法吗?
ValueError:值的长度与索引的长度不匹配
预期列:
'Electronics', 'Computers & Accessories', 'Cables & Accessories', 'Cables & Interconnects', 'USB Cables','Video Games', 'Sony PSP'
'Video Games', 'PlayStation 3', 'Accessories', 'Controllers', 'Gamepads'
'Cell Phones & Accessories', 'Accessories', 'Chargers', 'Travel Chargers','Video Games', 'Nintendo DS'
答案 0 :(得分:1)
将嵌套生成器与join
一起使用:
df["categories"]=[', '.join(item for sublist in x for item in sublist) for x in df["categories"]]
如果在较大的DataFrame
中,性能很重要:
from itertools import chain
df["categories"] = [', '.join(chain.from_iterable(x)) for x in df["categories"]]
print (df)
categories
0 Electronics, Computers & Accessories, Cables &...
1 Video Games, PlayStation 3, Accessories, Contr...
2 Cell Phones & Accessories, Accessories, Charge...
时间 :(实际数据应该有所不同,最好先进行测试):
df = pd.concat([df] * 10000, ignore_index=True)
In [45]: %timeit df["c1"]=[', '.join(item for sublist in x for item in sublist) for x in df["categories"]]
39 ms ± 706 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
In [46]: %timeit df["c2"]=[', '.join(chain.from_iterable(x)) for x in df["categories"]]
22.1 ms ± 258 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
In [47]: %timeit df['c3'] = df["categories"].apply(lambda x: ', '.join(str(r) for v in x for r in v))
66.7 ms ± 695 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
答案 1 :(得分:0)
您需要列表理解
df['col'] = df.col.apply(lambda x: ', '.join(str(r) for v in x for r in v))
输出:
col
0 Electronics, Computers & Accessories, Cables &...
1 Video Games, PlayStation 3, Accessories, Contr...
2 Cell Phones & Accessories, Accessories, Charge...