How to save pandas groups to separate files

后端 未结 2 1448
甜味超标
甜味超标 2021-01-17 19:17

I\'ve created individual groups of my data using the following statements:

df = pd.read_csv(file_path)

grouped = df.groupby(df.some_parameter)
相关标签:
2条回答
  • 2021-01-17 19:50

    This answer was very helpful to me - thanks @mkln.

    I just wanted to add something specific to my own use case, which relates to the original point about file-naming ('Some Text' + name = group).

    You could add the name and additional text, for example current date, to each csv filename, so I will create a function to return the current date and then use this for the filename.

    Therefore:

    from datetime import datetime
    
    def cur_date():
        return datetime.now().strftime("%Y-%m-%d")
    
    for name, group in grouped:
        group.to_csv('{}_{}.csv'.format(name, cur_date()))
    
    0 讨论(0)
  • 2021-01-17 19:56

    You were almost there

    for name, group in grouped:
        group.to_csv(path_to_disk)
    
    0 讨论(0)
提交回复
热议问题