python - 尝试按城市将数据从 csv 导出到文本

标签 python pandas

我正在尝试使用 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/

相关文章:

pandas - 我如何在不对 Pandas 进行排序的情况下解压?

python - `ValueError: cannot reindex from a duplicate axis` 是什么意思?

python - 导入错误 : cannot import name 'HTTPError' from urllib3. 异常

python - 在 nginx 上使用 Django 设置套接字

python - 如何在每一行提取列表的特定部分?

python - 新的 DataFrame 是每天的平均值

python - 如何处理-AttributeError : 'NoneType' object has no attribute 'patient_id'

python - 具有许多字段的 Django 过滤器

python - 合并数据框而不重复列

python - 带次要 y 轴的 Pandas 条形图 : hide grid line below plot