填充 pandas 数据框中缺失的数据 [英] Filling in missing data in pandas dataframe

查看:56
本文介绍了填充 pandas 数据框中缺失的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有两个索引的 Pandas 数据框

I have a Pandas dataframe with two indexes

                              Column1
indexA   indexB                        
1001     aaa                        1
         bbb                        1
         ccc                        1
1002     ddd                        1
         eee                        1

并且希望 indexB 对于 indexA 的每个值都具有相同的值:

and would like indexB to have the same values for each value of indexA:

                              Column1
indexA   indexB                        
1001     aaa                        1
         bbb                        1
         ccc                        1
         ddd                        0
         eee                        0
1002     aaa                        0
         bbb                        0
         ccc                        0
         ddd                        1
         eee                        1

我的第一个想法是取消堆叠,用 0 填充然后堆叠它,但这似乎有点矫枉过正.有没有更简单的方法?

My first thought was to unstack, fillna with 0 and then stack it, but this seems like overkill. Is there an easier method?

下面亚历山大的回答虽然需要很长时间(我的原始数据帧有 350k 行).我稍微改变了这个解决方案:

Alexander's answer below works though it takes a long time (my original dataframe has 350k rows). I changed that solution slightly:

df =  pd.read_sql(sql=sql, con=db_eng, index_col=index)
idx = pd.MultiIndex.from_product([df.index.levels[0], df.index.levels[1]], names=df.index.names)
df.reindex(idx).fillna(value=0)

发帖后也发现了这两个问题:

Also found these two questions after posting this:

推荐答案

可能有更好的方法来做到这一点.我使用 pd.MultiIndex.from_product 创建了一个新的 MultiIndex.然后我创建了一个带有虚拟值的新数据框,加入了现有的 dtaframe,并删除了虚拟列.

There is probably a better way to do this. I created a new MultiIndex using pd.MultiIndex.from_product. I then created a new dataframe with a dummy value, joined the existing dtaframe, and deleted the dummy column.

df = pd.DataFrame({'index_0': ['a', 'a', 'b', 'b', 'b'], 
                   'index_1': ['A', 'B', 'A', 'B', 'C'], 
                   'vals': [1, 2, 3, 4, 5]}).set_index(['index_0', 'index_1'])

>>> df 
                 vals
index_0 index_1      
a       A           1
        B           2
b       A           3
        B           4
        C           5

idx = pd.MultiIndex.from_product([df.index.levels[0], df.index.levels[1]], 
                                 names=df.index.names)
new_df = pd.DataFrame({'_dummy_': [1] * len(idx)}, index=idx).join(df)
del new_df['_dummy_']

>>> new_df
                 vals
index_0 index_1      
a       A           1
        B           2
        C         NaN
b       A           3
        B           4
        C           5

这篇关于填充 pandas 数据框中缺失的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆