简体   繁体   English

pandas - 减去 2 个类似的数据框数据透视表

[英]pandas - Subtract 2 similar pivot table of data frame

I have a 36 rows x 36 columns dataframe of pivot table which I transform using code below:我有一个 36 行 x 36 列的数据透视表数据框,我使用以下代码进行转换:

df_pivoted = pd.pivot_table(df,index='From',columns='To',values='count')
df_pivoted.fillna(0,inplace=True)

I transpose the same dataframe using this code:我使用以下代码转置相同的数据帧:

df_trans = df_pivoted.transpose()

and want to substract those two dataframes with this code:并想用以下代码减去这两个数据帧:

new_pivoted = df_pivoted - df_trans

It gives me 72 rows x 72 columns dataframe with NaN value in all cell.它给了我 72 行 x 72 列的数据框,所有单元格中都有 NaN 值。

Then I try to use other code:然后我尝试使用其他代码:

delta = df_pivoted.subtract(df_trans, fill_value=0)

However, it yields 72 rows x 72 columns with dataframe that looks like this:但是,它产生 72 行 x 72 列的数据框,如下所示: 在此处输入图片说明

Please help me to find the difference between the original dataframe with the transpose dataframe.请帮我找出原始数据帧与转置数据帧之间的区别。

After transforming of you DataFrame (pivot table) you have new DataFrame where columns become Indices and vise versa.转换您的 DataFrame(数据透视表)后,您将拥有新的 DataFrame,其中的列变为索引,反之亦然。 Now when you subtract on df from another Pandas use columns and Indices and fill NaN in the rest.现在,当您从另一个 Pandas 中减去 df 时,使用列和索引并在其余部分填充 NaN。

if you need to subtract values no matter of index and columns use:如果无论索引和列如何都需要减去值,请使用:

delta = df_pivoted.values - df_trans.values

If you want to keep Columns and Index of df_trans in df_pivoted:如果您想在 df_pivoted 中保留 df_trans 的列和索引:

df_trans = pd.DataFrame(data=df_pivoted.transpose().values, 
                        index=df_pivoted.index,
                        columns = df_pivoted.columns)

delta = df_pivoted - df_trans

Now simple subtraction works.现在简单的减法工作。

Hope that helps!希望有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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