简体   繁体   English

填充DataFrame Pandas Python

[英]Filling DataFrame Pandas Python

I have a similar dataset, and even though the code gives me the right output; 我有一个类似的数据集,即使代码为我提供了正确的输出; I do not want to use three for loops. 我不想使用三个for循环。 Is there a way to do this in a better way? 有没有办法更好地做到这一点?

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, using reindex 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.

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