Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/307.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_Dataframe - Fatal编程技术网

使用多索引数据帧更新二维数据帧Python

使用多索引数据帧更新二维数据帧Python,python,pandas,dataframe,Python,Pandas,Dataframe,我正在尝试用一些数据创建热图。为此,我创建了一个空的二维数据帧 dft=pd.DataFrame(0,index=matrix\u values\u index,columns=matrix\u values\u columns) 这给了我一个58x58矩阵 另一方面,excel电子表格中有一些数据,我已将其转换为多索引数据框 df2=heatmap\u values.groupby(['ID Requester','ID Supplier']).agg({'ID Supplier':'cou

我正在尝试用一些数据创建热图。为此,我创建了一个空的二维数据帧

dft=pd.DataFrame(0,index=matrix\u values\u index,columns=matrix\u values\u columns)

这给了我一个58x58矩阵

另一方面,excel电子表格中有一些数据,我已将其转换为多索引数据框

df2=heatmap\u values.groupby(['ID Requester','ID Supplier']).agg({'ID Supplier':'count'})

df2.rename(列={'ID Supplier':'No.Interdependencies'})

第一个索引是二维数据帧的索引

第二个索引是二维数据帧的列

是否有一种方法可以使用多索引数据帧的值更新二维数据帧,而不在其上循环

我一直在互联网上寻找解决方案,但至今没有成功

你对这个问题有什么建议吗

提前感谢。

如果某些索引或列名丢失,请使用with,而不是您的解决方案:

dft = (pd.crosstab(heatmap_values['ID Requester'],heatmap_values['ID Supplier'])
         .reindex(index=matrix_values_index, columns= matrix_values_columns, fill_value=0))
对于相同的输出,您的解决方案应该更改为,并且
reindex

df2 = heatmap_values.groupby(['ID Requester','ID Supplier']).agg({'ID Supplier':'count'})

df2 = df2.rename(columns={'ID Supplier': 'No. Interdependencies'})

dft = (df2['No. Interdependencies'].unstack(fill_value=0)
                                   .reindex(index=matrix_values_index,
                                            columns= matrix_values_columns, 
                                            fill_value=0))

我正在尝试你的方法,但不成功。我已将(df['ID Requester'],df['ID Supplier'])替换为(df2.index.names[0],df2.index.names[1]),因为它是一个多索引数据帧,但没有成功far@Nikolas-将您的解决方案添加到我的答案中。您好@jezrael我使用了您的一些提示,并最终成功:dfn=df2.unstack()dfn_reduced=dfn.xs('ID IPM Supplier',axis=1,drop_level=True)。fillna(0)dfn_full=dfn_reduced.reindex(index=matrix_values_index,columns=matrix_values_columns,fill_value=0)–@Nikolas-因此数据不同于
df2=heatmap_值。groupby(['ID Requester','ID Supplier'])。agg({'ID Supplier':'count})df2=df2。重命名(columns={'ID Supplier':'No.Interdependencies'})
,因此不可能使用
df2['No.Interdependencies'].unstack(fill_value=0)
代替
dfn=df2.unstack()dfn_reduced=dfn.xs('ID IPM Supplier',axis=1,drop_level=True)。fillna(0)