'how to copy the row value as per row name into another row using pyhton
Field_Name = ['Field Name', 'Success', 'Failure', '%']
thewriter = csv.DictWriter(f, fieldnames=Field_Name)
# thewriter.writeheader()
thewriter.writerow({'Field Name': 'Extraction Accuracy', '%': extraction_accuracy})
thewriter.writerow({'Field Name': 'Classification Accuracy', '%': " "})
i want to copy "DOC-TYPE", % row value into "Classification Accuracy"
Solution 1:[1]
Something like this would work.
- You just read the original data from the file.
- extract the value from the
DOC-Typerow - insert value into the
Classification Accuracyrow - write the data back to same file
from csv import DictReader, DictWriter
with open(csvfile) as csvf:
reader = csv.DictReader(csvf) # read data from csv file
for row in reader:
# find "DOC-TYPE" row and get value of "%"
if row["Field Name"] == "DOC-TYPE":
value = row["%"] # assign value to `value`
break
# find "Classif.. Acc.." row and set the "%" key's value to `value`
for row in reader:
if row["Field Name"] == "Classification Accuracy":
row["%"] = value # copy value into this cell
break
# then you would just write back to the same file
Field_Name = ['Field Name', 'Success', 'Failure', '%']
with open(csvfile, 'wt') as csvf:
writer = csv.DictWriter(csvf, fieldnames=Field_Name)
for row in reader:
writer.writerow(row)
For further info on the csv.DictReader see the python docs https://docs.python.org/3/library/csv.html?highlight=csv#csv.DictReader
Solution 2:[2]
Unfortunately, you have to read the file and get the row pf DOC-TYPE. When you found the row you can extract the value and paste it to your new row. I am not aware of any other way to get the row by the first entry, than reading through the file until you found it by your own.
Solution 3:[3]
If your current rows are fixed in space (that is, immutable in order), you can do the follwing:
list_read = csv.reader(f)
current_list = list(list_read)
desired_value = current_list[13][-1]
# Or it could be current_list[-3][-1] if all the rows depicted finish until 15
Finally, proceed to use:
thewriter.writerow({'Field Name': 'Classification Accuracy', '%': desired_value })
Hope that this could be of use :)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | thomas |
| Solution 3 | Pedro Germán |

