[英]pandas: fill multiple empty dataframes
我声明多个空数据框,如下所示:
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方式?
原因:在这里,我只给出了两个数据帧,但是,真正的问题是还有更多的数据帧,我必须定期对其进行更新。
使用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')
假设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.