Python Pandas根据日期从1个表创建5个excel文件

问题描述 投票:0回答:2

日期存储为日期时间。我不想硬编码日期。我希望脚本查找具有相同日期的列,将它们组合在一起并导出到文件名中包含日期的文件。

    Account  |  datestart   |   Charge  |
   ----------+--------------+-----------+
    123A     |  2019-03-14  |   7299    |
    5866A    |  2019-03-14  |   4000    | 
    12321A   |  2019-03-14  |   5000    |
    312332A  |  2019-03-13  |   5000    |
    586A     |  2019-03-13  |   4000    |
    967567A  |  2019-03-13  |   5167.66 |
    3437A    |  2019-03-12  |   9187.2  |
    956734A  |  2019-03-12  |   4482    |
    36736A   |  2019-03-11  |   4101    |
    3567356A |  2019-03-10  |   4007.85 |
    9467A    |  2019-03-10  |   5097.18 |

该脚本应导出到5个文件。每个文件仅包含具有特定日期的数据。

例如,第一个文件应该是这样的

    Account  |  datestart   |   Charge  |
   ----------+--------------+-----------+
    123A     |  2019-03-14  |   7299    |
    5866A    |  2019-03-14  |   4000    | 
    12321A   |  2019-03-14  |   5000    |

第二个文件应该是这样的

    Account  |  datestart   |   Charge  |
   ----------+--------------+-----------+
    312332A  |  2019-03-13  |   5000    |
    586A     |  2019-03-13  |   4000    |
    967567A  |  2019-03-13  |   5167.66 |

第一个文件应保存为file_031419,第二个文件应保存为file_031319。我将要查看的数据将有一个日期变量,因此文件名应该是动态的,基于文件中的日期。

这是我尝试过的一些代码

filedates = list(none['datestart'].unique())

for date in filedates: 
   filename = 'File_'+list(set(pd.to_datetime(none.loc[idx, 'datestart']).dt.strftime('%m%d%y')))[0]+'.xlsx'
   none.loc[idx, 'datestart'].to_excel(filename) 
python pandas loops date export-to-excel
2个回答
2
投票

您可以尝试以下方法:

for i , g in df.groupby('datestart'):
    g.to_csv('C:\\path\\'+'file_'+ \
         g.datestart.dt.strftime('%y%m%d').astype(str).iloc[0] +'.csv',index=False)

1
投票

这与anky_91没什么不同,但是文件名与OP提出的相同,并且它可能更容易理解,因为一旦在小函数save_group上工作它就非常灵活

首先,我们重现您的相同数据集

import pandas as pd


txt = """123A     |  2019-03-14  |   7299    |
    5866A    |  2019-03-14  |   4000    | 
    12321A   |  2019-03-14  |   5000    |
    312332A  |  2019-03-13  |   5000    |
    586A     |  2019-03-13  |   4000    |
    967567A  |  2019-03-13  |   5167.66 |
    3437A    |  2019-03-12  |   9187.2  |
    956734A  |  2019-03-12  |   4482    |
    36736A   |  2019-03-11  |   4101    |
    3567356A |  2019-03-10  |   4007.85 |
    9467A    |  2019-03-10  |   5097.18 |"""

txt = txt.split("\n")
txt = [t.split("|")[:-1] for t in txt]

df = pd.DataFrame(txt, columns=["Account", "datestart", "Charge"] )
for col in df.columns:
    df[col] = df[col].str.rstrip().str.lstrip()

df["datestart"] = df["datestart"].astype("M8[us]")  

然后为每个组保存为csv文件

def save_group(grp):
    fn = grp["datestart"].dt.strftime('%m%d%y').astype(str).iloc[0]
    fn = "".join(["file_",fn, ".csv"])
    grp.to_csv(fn, index=False)

要将它用于每个组,您只需使用apply即可

df.groupby("datestart").apply(lambda x: save_group(x))
© www.soinside.com 2019 - 2024. All rights reserved.