Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

trying to export data by city from csv to text

Tags:

python

pandas

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
like image 496
zul Avatar asked Dec 18 '25 21:12

zul


1 Answers

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")
like image 97
koPytok Avatar answered Dec 21 '25 12:12

koPytok



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!