Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
177 views
in Technique[技术] by (71.8m points)

python - Extracting individual rows from dataframe

I am currently doing one of my final assignment and I have a CSV file with a few columns of different data.

Currently interested in extracting out a single column and converting the individual rows into a txt file.

Here is my code:

import pandas as pd
import csv

df = pd.read_csv("AUS_NZ.csv")

print(df.head(10))

print(df["content"])

num_of_review = len(df["content"])

print(num_of_review)

for i in range (num_of_review):
    with open ("{}.txt".format(i),"a", encoding="utf-8") as f:
        f.write(df["content"][i])

No issue with extracting out the individual rows. But when I examine the txt files that was extracted and look at the content, I noticed that it copied out the text (which is what I want) but it did so twice (which is not what I want).

Example: "This is an example of what the dataframe have at that particular column which I want to convert to a txt file."

This is what was copied to the txt file: "This is an example of what the dataframe have at that particular column which I want to convert to a txt file.This is an example of what the dataframe have at that particular column which I want to convert to a txt file."

Any advise on how to just copy the content once only?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Thanks! While thinking about how to rectify this, I came to the same conclusion as you. I made a switch from "a" to "w" and it solved that issue.

Too used to append so I tried that before I tried write.

The correct code:

import pandas as pd
import csv

df = pd.read_csv("AUS_NZ.csv")

print(df.head(10))

print(df["content"])

num_of_review = len(df["content"])

print(num_of_review)

for i in range (num_of_review):
    with open ("{}.txt".format(i),"w", encoding="utf-8") as f:
        f.write(df["content"][i])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...