Pandas:填充多个空数据帧

2024-04-19 18:51:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我声明了多个空数据帧,如下所示:

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

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

我可以使用fillna如下:

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

什么是同时填充多个数据帧的更为python的方法?你知道吗


原因:这里我只给出了两个数据帧,然而,真正的问题是有更多的数据帧,我必须定期更新。你知道吗


Tags: columns数据声明dataframeindexrangevariablespd
3条回答

使用for循环:

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

也许可以用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

此外,参数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')

假设您的数据类型和索引相同,您可以使用字典理解,其中每个数据帧都是字典中的一个值。你知道吗

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}

相关问题 更多 >