[英]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.