i am trying to export data of different years that is grouped by city from a csv to a text file using python but i am not sure how to go about it
having a csv file eg
year rainfall city
2019 20 A
2019 10 B
2018 18 A
2018 9 B
import pandas as pd #used for other function in program
data = pd.read_csv(file.csv)
...
city=[]
for col in csv.columns:
if "city" in col.lower():
citylist = list(csv[col])
for ct in citylist:
if ct not in city:
city.append(ct)
for numcity in city
textfile= open(file.txt,"w")
textfile.write()
textfile.close
The outcome trying to achieve
A.txt
year rainfall city
2019 20 A
2018 18 A
B.txt
year rainfall city
2019 10 A
2018 9 A
If you need to split dataframe by city, you can use groupby:
for city, grp in data.groupby("city"):
grp.to_csv(city + ".txt", index=False, sep="\t")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With