在单个数据框中创建具有一定行数的多个数据框,然后在导入后从单个文件创建下一个数据框

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

我有一个包含 3 年数据(时间序列)的 csv 文件。在 python 中导入数据后,我创建了数据框。问题是索引从 0 开始并继续,但我希望每个月的索引可以再次从 0 开始,这样当我在图表上绘制天数时从 0 开始。如何通过提取为不同的月份创建多个数据帧单个数据框每次只有一定数量的行

试图创建一个空数据框并在其中导入一定数量的行(二月),但它采用的索引仍然是 31,因为一月结束于 30(如果我们从 0 开始) 在 python 中导入 csv 创建了一个数据框 使用 iloc 函数用于 jan 数据(行索引从 0 到 31) 对于 2 月,我从 31:59 开始进行行访问,因此它显示在印刷品中以及从 31 开始的情节 我想让每个月从 1

开始
python dataframe extract
1个回答
0
投票

IIUC,在 dictcomp

 中使用 
sample
/
reset_index :

import numpy as np
import pandas as pd
​
dates = pd.date_range(start="2021-01-01", end="2023-12-31", freq="D") # 3 years of data
df = pd.DataFrame({"value": np.random.rand(len(dates))}, index=dates) # ---------------
​
dfs = {f"{n.month_name()}_{n.year}": g.reset_index(drop=True) for n, g in df.resample("M")}

输出:

{'January_2021':        value
 0   0.061758
 1   0.727779
 2   0.330694
 3   0.987844
 4   0.558633
 ..       ...
 26  0.866195
 27  0.304799
 28  0.972036
 29  0.691263
 30  0.966565
 
 [31 rows x 1 columns],
 'February_2021':        value
 0   0.426072
 1   0.866830
 2   0.662469
 3   0.449467
 4   0.335500
 ..       ...
 23  0.409101
 24  0.790689
 25  0.946540
 26  0.022972
 27  0.648176
 
[28 rows x 1 columns],
...
© www.soinside.com 2019 - 2024. All rights reserved.