代码之家  ›  专栏  ›  技术社区  ›  Lumos

以dataframe名称作为文件名在循环中导出csv

  •  0
  • Lumos  · 技术社区  · 5 年前

    我有一个数据帧列表,我希望对我的函数进行操作,并将输出单独导出到我的目录中,数据帧名称作为文件名(例如,“weather”),加上一个固定的结尾(例如“_perYear”)。我该怎么做?我的代码结构如下:

    df_list = [weather, air, ground]
    for df in df_list:
        df_perYear = myFunction1(data = df) # my own function
        df_perYear.to_csv("..\weather_perYear.csv") # how to loop the filename?
    

    预期输出:导出三个csv文件,文件名为 weather_perYear.csv , air_perYear.csv , ground_perYear.csv .

    谢谢

    0 回复  |  直到 5 年前
        1
  •  1
  •   wombat    5 年前

    如果我没弄错你的问题,你想要这样的东西:

    for df in df_list:
        name = [x for x in globals() if globals()[x] is df][0]
        print(f"..\\{name}_perYear.csv")
    

    但这并不好,如果这是熊猫,你可以考虑使用 df.name 如果数据帧不存在,则设置其名称。

    另见 Get the name of a pandas DataFrame

    推荐文章