[英]Filling DataFrame Pandas Python
我有一個類似的數據集,即使代碼為我提供了正確的輸出; 我不想使用三個for循環。 有沒有辦法更好地做到這一點?
import pandas as pd
col = ["a","b","c","d"]
index = ["0","1","2","3"]
dict_ = {("0","a"):8,
("1","a"):3,
("3","b"):2}
df = pd.DataFrame(columns=col,index=index)
for i in range(len(dict_)):
for j in range(len(df)):
for k in range(len(df)):
if (str(df.index[j]),str(df.columns[k])) == dict_.keys()[i]:
df.at[df.index[j],df.columns[k]] = dict_.values()[i]
print df
IIUC,使用reindex
pd.Series(dict_).unstack().reindex(index=index,columns=col)
Out[245]:
a b c d
0 8.0 NaN NaN NaN
1 3.0 NaN NaN NaN
2 NaN NaN NaN NaN
3 NaN 2.0 NaN NaN
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.