我正在尝试使用 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
最佳答案
如果需要按城市拆分dataframe,可以使用groupby
:
for city, grp in data.groupby("city"):
grp.to_csv(city + ".txt", index=False, sep="\t")
关于python - 尝试按城市将数据从 csv 导出到文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58430735/