【问题标题】:Pandas: Split large file into seperate files by Date, preserving original ordering.Pandas:按日期将大文件拆分为单独的文件,保留原始顺序。
【发布时间】:2018-01-04 02:24:44
【问题描述】:

我有一个非常大的数据框,其日期为 Index ,每天涵盖多年的时间。每天都包含多个值。

      Date (DT_index)   Description   Value1
  1      2015-01-12     stringvalue    10
  2      2015-01-12     stringvalue    12
  3      2015-01-12     stringvalue    14
  4      2015-02-12     stringvalue    16
  5      2015-02-12     stringvalue   348
  6      2015-09-12     stringvalue     1
  7      2015-09-12     stringvalue     9
                  (.....)
8456     2017-11-03     stringvalue    10
8457     2017-11-03     stringvalue   111
8458     2017-11-04     stringvalue    29

我想要的是根据月/年将此 csv 拆分为单独的文件。 (所以文件如:12-2015.csv、01-2016.csv、02-2016.csv)

我已将大型 csv 加载到 pandas df 中,并按月份对其进行分组

dfgp = df.groupby(pd.TimeGrouper(freq='M'))

但对我来说唯一可用的操作似乎是“sum”或“avg”。 我不希望这样,我想按月对大型 DF 进行切片,而不是执行更改或聚合数据的 .apply 操作。

我也试过这个代码:

dfgp = [group[1] for group in df.groupby(df.index.date)]

for x in result:
    name = str(x.index.date.month.year)
    x.to_csv(name, sep=';')

这种方法非常接近。我有两个问题。 1.我的命名方法不起作用:

'numpy.ndarray' object has no attribute 'month'
  1. 当我删除我的 name 方法时,它会遍历文件。但是这些组是按天制作的(例如:2015-12-13,有 6 个条目,而不是 2015-12-alldays,有 238 个条目)

我要更正此代码的最后一个问题:

result = [group[1] for group in df.groupby(df.index.date.month)]

但这只是抛出了和以前一样的错误:

'numpy.ndarray' object has no attribute 'month'

有谁知道我做错了什么?

【问题讨论】:

  • 您实际上并不想按月分组,您只想按月索引。

标签: python pandas pandas-groupby


【解决方案1】:

我们试试吧:

for n,g in df.groupby(pd.Grouper(freq='M')):
    name = n.strftime('%Y%m') + '.csv'
    g.to_csv(name, sep=';')

【讨论】:

  • 你的意思是 to_csv ;)
【解决方案2】:

可能有更好的(更通俗的)方法来做到这一点:

import os

# this just assumes that you want to save where the 
# current file is located
csv_path = 'path\to\your.csv'
data_path = os.path.dirname(csv_path)

# read the csv and add a simple string column for indexing
df = pd.read_csv(csv_path)
df['date_filters'] = df['Date'].str.strftime('%m-%Y')

# iterate over the months present
for month in df['date_filters'].unique():
    # slice out the month
    month_df = df[df['date_filters'] == month]
    # drop the string column you added before saving
    month_df.drop('date_filters', inplace=True, axis=1)
    # make the path and save
    month_path = os.path.join(data_path, month+'.csv')
    month_df.to_csv(month_path, index=False) 

【讨论】:

    猜你喜欢
    • 2019-06-24
    • 1970-01-01
    • 2020-08-31
    • 2022-08-17
    • 2014-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多