pandas将带方括号的列作为字符串而不是列表导入

wb1gzix0  于 2021-07-13  发布在  Java
关注(0)|答案(1)|浏览(423)

使用 pd.read_csv 我正在导入Dataframe。其中一列包含字符串列表。例如:

>>> df['topic'].head(5)
0    ['ECONOMIC PERFORMANCE', 'ECONOMICS', 'EQUITY ...
1    ['CAPACITY/FACILITIES', 'CORPORATE/INDUSTRIAL']
2    ['PERFORMANCE', 'ACCOUNTS/EARNINGS', 'CORPORAT...
3    ['PERFORMANCE', 'ACCOUNTS/EARNINGS', 'CORPORAT...
4    ['STRATEGY/PLANS', 'NEW PRODUCTS/SERVICES', 'C...
Name: topic, dtype: object

虽然此列应该充满列表,但pandas正在将其作为字符串导入。我怎样才能让Pandas将其作为列表列导入?

chy5wohz

chy5wohz1#

可以将包含字符串的列转换为包含字符串的python列表 ast.literal_eval . 例如:

from ast import literal_eval

df["topic"] = df["topic"].apply(literal_eval)
print(df)

印刷品:

topic
0    [ECONOMIC PERFORMANCE, ECONOMICS, EQUITY]
1  [CAPACITY/FACILITIES, CORPORATE/INDUSTRIAL]
2  [PERFORMANCE, ACCOUNTS/EARNINGS, CORPORATE]
3  [PERFORMANCE, ACCOUNTS/EARNINGS, CORPORATE]
4      [STRATEGY/PLANS, NEW PRODUCTS/SERVICES]

相关问题