如何将具有列表值的pandas列连接到一个列表中? [英] How to concatenate pandas column with list values into one list?
问题描述
我有一个数据框,它的列之一在每个索引处都有一个列表.我想将这些列表合并为一个列表.我正在使用
I have a dataframe with one of its column having a list at each index. I want to concatenate these lists into one list. I am using
ids = df.loc[0:index, 'User IDs'].values.tolist()
但是,这导致
['[1,2,3,4......]']
这是一个字符串.不知何故,我的列表列中的每个值都是str
类型.我尝试使用list()
,literal_eval()
进行转换,但是它不起作用. list()
将列表中的每个元素转换为字符串,例如从[12,13,14...]
到['['1'',','2',','1',',','3'......]']
.
However, this results in
['[1,2,3,4......]']
which is a string. Somehow each value in my list column is type str
. I have tried converting using list()
, literal_eval()
but it does not work. The list()
converts each element within a list into a string e.g. from [12,13,14...]
to ['['1'',','2',','1',',','3'......]']
.
如何将具有列表值的pandas列连接到一个列表中?请帮忙,我在上面敲了几个小时.
How to concatenate pandas column with list values into one list? Kindly help out, I am banging my head on it for several hours.
推荐答案
考虑数据框df
df = pd.DataFrame(dict(col1=[[1, 2, 3]] * 2))
print(df)
col1
0 [1, 2, 3]
1 [1, 2, 3]
pandas
最简单的答案
pandas
simplest answer
df.col1.sum()
[1, 2, 3, 1, 2, 3]
numpy.concatenate
np.concatenate(df.col1)
array([1, 2, 3, 1, 2, 3])
chain
from itertools import chain
list(chain(*df.col1))
[1, 2, 3, 1, 2, 3]
回复评论:
我认为您的专栏是字符串
response to comments:
I think your columns are strings
from ast import literal_eval
df.col1 = df.col1.apply(literal_eval)
如果相反,您的列是看起来像列表的字符串值
If instead your column is string values that look like lists
df = pd.DataFrame(dict(col1=['[1, 2, 3]'] * 2))
print(df) # will look the same
col1
0 [1, 2, 3]
1 [1, 2, 3]
但是pd.Series.sum
不能正常工作.
df.col1.sum()
'[1, 2, 3][1, 2, 3]'
我们需要像对待文字一样评估字符串,然后sum
We need to evaluate the strings as if they are literals and then sum
df.col1.apply(literal_eval).sum()
[1, 2, 3, 1, 2, 3]
这篇关于如何将具有列表值的pandas列连接到一个列表中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!