【问题标题】:Convert dataframe column into set of text files将数据框列转换为一组文本文件
【发布时间】:2023-01-25 19:57:02
【问题描述】:

我有一个包含 topickeywords 列的数据框,如下所示:

topic   keyword
    0   ['player', 'team', 'word_finder_unscrambler', ...
    1   ['weather', 'forecast', 'sale', 'philadelphia'...
    2   ['name', 'state', 'park', 'health', 'dog', 'ce...
    3   ['game', 'flight', 'play', 'game_live', 'play_...
    4   ['dictionary', 'clue', 'san_diego', 'professor...

需要分别为每个主题创建一个文本文件,即 topic1.txt、topic2.txt、....topic20.txt 并且主题文本文件应在关键字列内的换行符中包含字符串,如下所示:

topic1.txt file should contain:

player
team
word_finder_unscrambler
etc

【问题讨论】:

    标签: python-3.x pandas dataframe


    【解决方案1】:

    对于 DataFrame 的每一行,使用 topic 列按名称创建新的 txt 文件,并添加 1

    import  csv
    
    for t, k in zip(df['topic'], df['keyword']):
        with open(f"topic{t + 1}.txt","w") as f:
            wr = csv.writer(f,delimiter="
    ")
            wr.writerow(k)
    

    编辑:因为 keyword 列中没有列表,只有字符串使用:

    import  csv, ast
    
    for t, k in zip(df['topic'], df['keyword']):
        with open(f"topic{t + 1}.txt","w") as f:
            wr = csv.writer(f,delimiter="
    ")
            wr.writerow(ast.literal_eval(k))
    

    【讨论】:

    • 由于主题列在列内,因此您上面的代码给出的输出为 [ ' p l a y e r ' , ' t e a m '
    猜你喜欢
    • 1970-01-01
    • 2016-04-14
    • 2015-11-14
    • 1970-01-01
    • 1970-01-01
    • 2022-11-03
    • 1970-01-01
    • 2022-01-22
    相关资源
    最近更新 更多