【问题标题】:Generate string set from csv file in Python在 Python 中从 csv 文件生成字符串集
【发布时间】:2019-05-15 01:28:12
【问题描述】:

请不要立即标记我的答案,因为我搜索了其他几个没有解决我问题的问题,例如this.

我正在尝试从 csv 文件生成一组 python 字符串。加载的 csv 文件打印出来的 pandas 数据帧结构如下:

   0
0  me
1  yes
2  it

对于一个项目,我需要将其格式化为如下所示

STOPWORDS = {'me', 'yes', 'it'}

我尝试通过以下代码做到这一点。

import pandas as pd

df_stopwords = pd.read_csv("C:/Users/Jakob/stopwords.csv", encoding = 'iso8859-15', header=-1)

STOPWORDS = {}
for index, row in df_stopwords.iterrows():
    STOPWORDS.update(str(row))

print(STOPWORDS)

但是,我收到此错误:

dictionary update sequence element #0 has length 1; 2 is required

当我使用STOPWORDS.update(str(row)) 时,我得到了这个错误:

'dict' object has no attribute 'add'

提前谢谢大家!

【问题讨论】:

  • 您需要dict 还是set?
  • 怎么样:set(df_stopwords[0])
  • 做类似set(df.values.ravel())的事情
  • @nixon 请将其发布为答案。我想把这归功于你!解决了我的问题。总之:请点赞! ;-P
  • @YOLO 您的解决方案也很完美。我想接受你的两个答案! :D 非常感谢!

标签: python pandas set


【解决方案1】:

您可以直接从数据框中的值创建set:

set(df.values.ravel())
{'me', 'yes', 'it'}

【讨论】:

    【解决方案2】:

    字典是键和值的映射。就像许多其他语言中的对象一样。由于您需要将其作为一个集合,因此将其定义为一个集合。以后不要改成一套。

    import pandas as pd
    
    df_stopwords = pd.read_csv("C:/Users/Jakob/stopwords.csv", encoding = 'iso8859-15', header=-1)
    
    STOPWORDS = set()
    for index, row in df_stopwords.iterrows():
        STOPWORDS.add(str(row))
    
    print(STOPWORDS)
    

    【讨论】:

    • 我需要大括号。这就是我不能使用列表的原因。谢谢!
    • 为什么需要大括号? Python 仅将它们用于特定的事情。
    • 我使用这个集合作为 wordcloud 库的输入,它需要一组不应该在词云中显示的词。它不接受列表。
    • 如果你将它格式化成一个字符串,你可以这样做:with_curly_brackets = str(STOPWORDS).replace("[", "{").replace("]", "}")
    • 啊...我明白了。我正在用更 Pythonic 的方式更新我的答案。
    【解决方案3】:

    您似乎需要将列中的值转换为列表,然后将该列表用作停用词。

    stopwords = df_stopwords['0'].tolist()
    --> ['me', 'yes', 'it']
    

    【讨论】:

      【解决方案4】:

      如已接受的答案here 中所述。您可能想使用itertuples(),因为它更快。

      STOPWORDS = set()
      for index, row in df_stopwords.itertuples():
          STOPWORDS.add(row)
      
      print(STOPWORDS)
      

      【讨论】:

        猜你喜欢
        • 2023-04-05
        • 2014-05-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-10-19
        • 1970-01-01
        • 2021-07-20
        • 2019-01-16
        相关资源
        最近更新 更多