我正在尝试使用python将按城市分组的不同年份的数据从csv导出到文本文件,但是我不确定如何处理
具有csv文件,例如
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
答案 0 :(得分:2)
如果您需要按城市划分数据框,则可以使用groupby
:
for city, grp in data.groupby("city"):
grp.to_csv(city + ".txt", index=False, sep="\t")