【发布时间】:2019-11-13 06:02:18
【问题描述】:
我选择了一些数据框,用于记录每日降雨量 (ppt_24H) 和洪水事件 (Fld)。它们看起来像这样:
ppt_24H Fld
01-01-2006 0.2 0.0
01-02-2006 0.6 0.0
01-03-2006 0.0 0.0
01-04-2006 11.5 1.0
01-05-2006 10.4 0.0
...
我使用“groupby”函数为每年生成数据帧,在是否发生洪水之间进行划分,并为 24 小时降雨间隔分配箱,如下所示:
my_intervals = np.array([(-0.1,0),(0.0,0.25),(0.25,0.5),(0.5,1),(1,2),(2,4),(4,6),(6,8),(8,12),(12,16),(16,20),(20,25),(25,30),(30,35),(35,40),(40,45),(45,50),(50,np.inf)])
bins = np.append(my_intervals[:, 0], my_intervals[-1, 1])
grouby函数如下:
Y2006 = pd.DataFrame(TM_YEAR06.groupby([pd.cut(TM_YEAR06['ppt_24H'], bins), 'Fld']).size().unstack().fillna(0).astype(int))
这成功拆分了数据,告诉我这些选定阈值之间的降雨天数与洪水相关(标记为“1.0”)或不相关(标记为“0.0”)。万岁。但是,索引根据每组阈值之间是否存在降雨事件而有所不同。例如,一年,它看起来像这样:
Fld 0.0 1.0
ppt_24H
(-0.1, 0.0] 46 1
(0.0, 1.0] 161 1
(1.0, 2.0] 62 0
(2.0, 3.0] 35 0
(3.0, 4.0] 11 1
(4.0, 5.0] 6 0
(5.0, 7.5] 14 0
(15.0, 20.0] 2 1
(25.0, 30.0] 2 0
(30.0, 40.0] 2 0
(60.0, 80.0] 2 0
这很好地拆分了数据,但它没有包括所有不满足条件的 bin。我还有 20 年需要合并到同一个 DataFrame 中,这些 DataFrame 正在重新调整不同的索引,但它们都没有所有索引。例如,这是另一个使用不同索引的虚构示例:
Fld 0.0 1.0
ppt_24H
(-0.1, 0.0] 54 1
(0.0, 1.0] 144 1
(1.0, 2.0] 62 0
(2.0, 3.0] 35 0
(3.0, 4.0] 11 1
(4.0, 5.0] 6 0
(7.5, 10] 14 0
(15.0, 20.0] 2 1
(25.0, 30.0] 6 0
(80.0, 100.0] 2 0
到目前为止,我已经尝试使用“my_intervals”中的列表来索引一个可以合并的空白数据框“YALL”,但这不起作用。这是我尝试过的代码:
YALL = pd.DataFrame(columns = [0.0 , 1.0], index=[(-0.1,0),(0.0,0.25),(0.25,0.5),(0.5,1),(1,2),(2,4),(4,6),(6,8),(8,12),(12,16),(16,20),(20,25),(25,30),(30,35),(35,40),(40,45),(45,50),(50,np.inf)])
这正如我所料,创建了一个充满 NaN 的数据框,但是当我尝试将 Y2006 合并到 YALL 时,使用:
Y2006 = YALL.merge(Y2006,left_index=True, right_index=True,how='left').fillna(0)
结果是这样的……:
Fld 0.0 1.0 0.0_x 1.0_x
ppt_24H
(-0.1, 0.0) 0 0 0 0
(0.0, 1.0) 0 0 0 0
(1.0, 2.0) 0 0 0 0
(2.0, 3.0) 0 0 0 0
(3.0, 4.0) 0 0 0 0
(4.0, 5.0) 0 0 0 0
(5.0, 7.5) 0 0 0 0
... and so on...
不是我所希望的...关于我可以做什么的任何想法?
编辑:
我设法弄清楚在 grouby 之后的输出索引是 CategoricalIndex,并且我想出了如何将我的索引更改为分类索引,使用这个令人愉快的低效代码:
CatIndex = pd.Series([(-0.1,0),(0.0,0.25),(0.25,0.5),(0.5,1),(1,2),(2,4),(4,6),(6,8),(8,12),(12,16),(16,20),(20,25),(25,30),(30,35),(35,40),(40,45),(45,50),(50,np.inf)], dtype="category")
idx= pd.Index(CatIndex).astype('category')
YALL = pd.DataFrame(index=idx)
但是现在我遇到了一个错误:
ValueError: setting an array element with a sequence.
对于这一行...:
---> 30 Y2006 = YALL.merge(Y2006,left_index=True, right_index=True,how='left').fillna(0)
任务继续……
【问题讨论】:
标签: python pandas indexing merge