gpt4 book ai didi

pandas - 如何确保所有行/列都出现在 pandas 交叉表中?

转载 作者:行者123 更新时间:2023-12-04 15:34:48 25 4
gpt4 key购买 nike

我正在为这样的转换矩阵计算一个简单的交叉表:

test_df = pd.DataFrame({'from': ['A', 'A', 'B', 'C'], 'to': ['A', 'B', 'B', None]}, 
columns=['from', 'to'])

pd.crosstab(test_df['from'], test_df['to'], dropna=False)

它产生以下矩阵:

   A | B
---------
A 1 | 1
---------
B 0 | 1

我希望它包括所有转换,即使它们为 0,如下所示:

   A | B | C
-------------
A 1 | 1 | 0
-------------
B 0 | 1 | 0
-------------
C 0 | 0 | 0

我是否缺少某些设置来执行此操作?我尝试检查选项,但找不到任何东西。

最佳答案

使用DataFrame.reindex最后:

i = test_df[['from','to']].stack().unique()

new_df = (pd.crosstab(test_df['from'], test_df['to'],dropna = False)
.reindex(index = i,columns=i,fill_value =0))
print(new_df)
to A B C
from
A 1 1 0
B 0 1 0
C 0 0 0

另一种方法: DataFrame.pivot_table

(test_df.pivot_table(index = 'from',columns = 'to',aggfunc = 'size',fill_value = 0)
.reindex(index = i,columns = i,fill_value = 0))

关于pandas - 如何确保所有行/列都出现在 pandas 交叉表中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60098390/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com