简体   繁体   English

大熊猫:填充多个空白数据框

[英]pandas: fill multiple empty dataframes

I'm declaring multiple empty dataframes as follows: 我声明多个空数据框,如下所示:

variables = pd.DataFrame(index=range(10),
                           columns=['P1', 'P2', 'P3'],
                          dtype='float64')

Q1 = pd.DataFrame(index=range(10),
                   columns=['P1H1', 'P1H2'],
                   dtype='float64')

I can use fillna as follows: 我可以按以下方式使用fillna:

variables = variables.fillna(0)
Q1 = Q1.fillna(0)

What is a more pythonic way of filling multiple dataframes simultaneously ? 什么是同时填充多个数据帧的更Python方式?


Reason: Here I have given only two dataframes, however, the real problem has many more dataframes, which I have to update periodically. 原因:在这里,我只给出了两个数据帧,但是,真正的问题是还有更多的数据帧,我必须定期对其进行更新。

Use a for loop: 使用for循环:

for df in (variables, Q1):
    df.fillna(0, inplace=True)

Maybe you can fill columns in DataFrame contructor with 0 , then fillna can be omited : 也许您可以用0填充DataFrame contructor列,然后可以省略fillna

import pandas as pd

variables = pd.DataFrame(index=range(10),
                         columns=['P1', 'P2', 'P3'],
                         data={'P1':[0],'P2':[0],'P3':[0]},
                         dtype='float64')

print variables   
    P1   P2   P3
0  0.0  0.0  0.0
1  0.0  0.0  0.0
2  0.0  0.0  0.0
3  0.0  0.0  0.0
4  0.0  0.0  0.0
5  0.0  0.0  0.0
6  0.0  0.0  0.0
7  0.0  0.0  0.0
8  0.0  0.0  0.0
9  0.0  0.0  0.0
Q1 = pd.DataFrame(index=range(10),
                  columns=['P1H1', 'P1H2'],
                  data={'P1H1':[0],'P1H2':[0]},
                  dtype='float64')
print Q1                   
   P1H1  P1H2
0   0.0   0.0
1   0.0   0.0
2   0.0   0.0
3   0.0   0.0
4   0.0   0.0
5   0.0   0.0
6   0.0   0.0
7   0.0   0.0
8   0.0   0.0
9   0.0   0.0

Also, parameter columns can be omited: 同样,可以忽略参数columns

import pandas as pd

variables = pd.DataFrame(index=range(10),
                         data={'P1':[0],'P2':[0],'P3':[0]},
                         dtype='float64')

Q1 = pd.DataFrame(index=range(10),
                  data={'P1H1':[0],'P1H2':[0]},
                  dtype='float64')

Given that your dtype and index is the same, you can use a dictionary comprehension where each dataframe is a value in the dictionary. 假设dtype和index相同,则可以使用字典理解,其中每个数据帧都是字典中的一个值。

cols = {'variables': ['P1', 'P2', 'P3'],
        'Q1': ['P1H1', 'P1H2']}

dfs = {key: pd.DataFrame(index=range(10), columns=cols[key], dtype='float64').fillna(0) 
       for key in cols}

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM