我有一个熊猫数据框列,看起来像:

Out[67]:
0      ["cheese", "milk...
1      ["yogurt", "cheese...
2      ["cheese", "cream"...
3      ["milk", "cheese"...


现在,最终我希望将其作为一个扁平列表,但是在尝试扁平化时,我注意到熊猫将["cheese", "milk", "cream"]视为str而不是list

我如何将其展平,所以最终得到:

["cheese", "milk", "yogurt", "cheese", "cheese"...]


[编辑]
因此,下面给出的答案似乎是:

s = pd.Series(["['cheese', 'milk']", "['yogurt', 'cheese']", "['cheese', 'cream']"])

s = s.str.strip("[]")
df = s.str.split(',', expand=True)
df = df.applymap(lambda x: x.replace("'", '').strip())
l = df.values.flatten()
print (l.tolist())


很好,已回答问题,已接受回答,但这对我来说是一个相当微妙的解决方案。

最佳答案

您可以使用numpy.flatten,然后使用平面嵌套的lists-see

print df
                  a
0    [cheese, milk]
1  [yogurt, cheese]
2   [cheese, cream]

print df.a.values
[[['cheese', 'milk']]
 [['yogurt', 'cheese']]
 [['cheese', 'cream']]]

l = df.a.values.flatten()
print l
[['cheese', 'milk'] ['yogurt', 'cheese'] ['cheese', 'cream']]

print [item for sublist in l for item in sublist]
['cheese', 'milk', 'yogurt', 'cheese', 'cheese', 'cream']


编辑:

你可以试试:

import pandas as pd

s = pd.Series(["['cheese', 'milk']", "['yogurt', 'cheese']", "['cheese', 'cream']"])

#remove []
s = s.str.strip('[]')
print s
0      'cheese', 'milk'
1    'yogurt', 'cheese'
2     'cheese', 'cream'
dtype: object

df = s.str.split(',', expand=True)
#remove ' and strip empty string
df = df.applymap(lambda x: x.replace("'", '').strip())
print df
        0       1
0  cheese    milk
1  yogurt  cheese
2  cheese   cream

l = df.values.flatten()
print l.tolist()
['cheese', 'milk', 'yogurt', 'cheese', 'cheese', 'cream']

10-04 16:27