简体   繁体   English

将 pandas df 保存到几个不同的 CSV 文件中

[英]save pandas df into several different CSV files

This is some code that will generate some random time series data.这是一些将生成一些随机时间序列数据的代码。 Ultimately I am trying to save each days, data into separate CSV files...最终,我试图将每一天的数据保存到单独的 CSV 文件中...

import pandas as pd 
import numpy as np 
from numpy.random import randint 

np.random.seed(10)  # added for reproductibility                                                                                                                                                                 

rng = pd.date_range('10/9/2018 00:00', periods=1000, freq='1H') 
df = pd.DataFrame({'Random_Number':randint(1, 100, 1000)}, index=rng)

I can print each days data with this:我可以用这个打印每天的数据:

for idx, days in df.groupby(df.index.date):
    print(days)

But how could I encorporate savings individual CSV files into a directory csv each file named with the first time stamp entry of month & day?但是,我如何将保存的单个 CSV 文件合并到一个目录csv每个文件都以月和日的第一个时间戳条目命名? (Code below does not work) (下面的代码不起作用)

for idx, days in df.groupby(df.index.date):
    for day in days:
        df2 = pd.DataFrame(list(day))
        month_num = df.index.month[0]
        day_num = df.index.day[0]

        df2.to_csv('/csv/' + f'{month_num}' + '_' + f'{day_num}' + '.csv')

You could iterate over all available days, filter your dataframe and then save.您可以遍历所有可用天数,过滤数据框,然后保存。

# iterate over all available days 
for date in set(df.index.date):  

    # filter your dataframe    
    filtered_df = df.loc[df.index.date == date].copy()

    # save it
    filename = date.strftime('%m_%d')  # filename represented as 'month_day'
    filtered_df.to_csv(f"./csv/{filename}.csv")  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用熊猫将数日长的数据框拆分为半小时的数据框,并将其另存为csv文件 - Splitting several days long dataframe into half-hourly dataframes using pandas and save them as csv-files 自动将多个json文件(具有不同的信息)读取并保存到不同的pandas数据帧 - Automate the read and save of several json files (with different information) to different pandas dataframes Pandas plot 在同一个条形图上具有不同变量的几个 df - Pandas plot several df with different variables on the same barplot 使用记录中的pandas索引几个csv文件? - indexing several csv files with pandas from records? 将包含长列表的Pandas df保存为csv文件 - Save Pandas df containing long list as csv file Python Pandas:强制将df保存在4位数的csv数值中 - Python Pandas: force to save a df in a csv numerical values with 4 digits 有没有一种方法可以根据数据框的列中的不同名称写入和保存多个csv或excel文件? - Is there a way to write & save several csv or excel files based on different names in a column of a dataframe? 将 CSV 转置为 DF Pandas - Transpose CSV into DF Pandas 根据 Pandas df 列值创建许多 CSV 文件 - Create many CSV Files based on Pandas df column value 使用pyinstaller在exe目录中保存df时pandas df to_csv冻结 - pandas df to_csv freezes when using pyinstaller to save the df in the exe directory
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM