Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Convert dataframe column into set of text files

I have a dataframe which contains topic and keywords column as shown below:

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...

Need to create a text file of each topic separately namely topic1.txt, topic2.txt,….topic20.txt and the topic text file should contain strings in newline inside keyword column something like this:

topic1.txt file should contain:

player
team
word_finder_unscrambler
etc

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

For each row of DataFrame create new txt file by name with topic column with add 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="\n")
        wr.writerow(k)

EDIT: Because no lists but strings in keyword column use:

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="\n")
        wr.writerow(ast.literal_eval(k))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading