gpt4 book ai didi

python - 无法从 CSV 中提取独特的单词

转载 作者:太空宇宙 更新时间:2023-11-04 10:09:07 25 4
gpt4 key购买 nike

我有一个 csv,如下所示:

    Description
0 ['boy']
1 ['boy', 'jumped', 'roof']
2 ['paris']
3 ['paris', 'beautiful', 'new', 'york']
4 ['lets', 'go', 'party']
5 ['refused', 'come', 'party']

我需要从这些数据中找出独特的词。所以输出将是:

    Unique Words
0 boy
1 jumped
2 roof
3 paris
4 beautiful
5 new
6 york

等等。我正在尝试使用 Pandas 和 Python 来做到这一点,但无法实现。我的代码是:

df = pd.read_csv('output.csv')
list(set(df.Description))
g = list(df['Description'].unique())
print(g)

这会抛出错误的输出,它只会抛出原始的 csv 数据帧。

最佳答案

你可以先把string列转换成list,我用的是ast.literal_eval。然后通过列表理解制作列表的平面列表,使用 set 并最后通过构造函数创建新的 DataFrame:

import ast

print (type(df.ix[0, 'Description']))
<class 'str'>

df.Description = df.Description.apply(ast.literal_eval)

print (type(df.ix[0, 'Description']))
<class 'list'>

#http://stackoverflow.com/q/952914/2901002
unique_data = list(set([item for sublist in df.Description.tolist() for item in sublist]))
print (unique_data)
['refused', 'jumped', 'go', 'roof', 'come', 'beautiful',
'paris', 'york', 'lets', 'new', 'boy', 'party']

print (pd.DataFrame({'Unique Words': unique_data}))
Unique Words
0 refused
1 jumped
2 go
3 roof
4 come
5 beautiful
6 paris
7 york
8 lets
9 new
10 boy
11 party

另一种没有ast的解决方案:

df.Description = df.Description.str.strip('[]').str.split(',')
print (df)
Description
0 ['boy']
1 ['boy', 'jumped', 'roof']
2 ['paris']
3 ['paris', 'beautiful', 'new', 'york']
4 ['lets', 'go', 'party']
5 ['refused', 'come', 'party']

unique_data = list(set([item.strip().strip("'") for sublist in df.Description.tolist() for item in sublist]))
print (unique_data)
['refused', 'jumped', 'go', 'roof', 'come', 'beautiful',
'paris', 'york', 'lets', 'new', 'boy', 'party']

print (pd.DataFrame({'Unique Words': unique_data}))
Unique Words
0 refused
1 jumped
2 go
3 roof
4 come
5 beautiful
6 paris
7 york
8 lets
9 new
10 boy
11 party

关于python - 无法从 CSV 中提取独特的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39384762/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com