Using Python, I'd like to create a loop to write text in a CSV file when a row contains text.
The original CSV format is:
user_id, text
0,
1,
2,
3, sample text
4, sample text
I'm seeking to add another column "text_number" that will insert the string "text_x", with x representing the number of texts in the column. I'd like to iterate this and increase the string's value by +1 for each new text. The final product would look like:
user_id, Text, text_number
0,
1,
2,
3, sample text, text_0
4, sample text, text_1
With my working code I can insert the header "text_number", but I'm having difficulty in putting together the loop for text_x.
import csv
output = list()
with open("test.csv") as file:
csv_reader = csv.reader(file)
for i, row in enumerate(csv_reader):
if i == 0:
output = [row+["text_number"]]
continue
# here's where I'm stuck
with open("output2.csv", "w", newline="") as file:
csv_writer = csv.writer(file, delimiter=",")
for row in output:
csv_writer.writerow(row)
Any thoughts?
pandas?"text_x", with x representing the number of texts in the columnwhat do you mean by number of texts?