Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/linux/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python中填充数据帧_Python_Pandas_Performance_Dataframe_For Loop - Fatal编程技术网

在Python中填充数据帧

在Python中填充数据帧,python,pandas,performance,dataframe,for-loop,Python,Pandas,Performance,Dataframe,For Loop,我有一个类似的数据集,即使代码给了我正确的输出;我不想使用三个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循环。有没有更好的办法

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

美丽的!谢谢:')@W-B。。is总是提供漂亮的解决方案和提示:-)+1