Pandas,Pivot表来自2列,其值为其中一列的计数

问题描述 投票:1回答:2

我有一个pandas数据帧:

+---------------+-------------+
| Test_Category | Test_Result |
+---------------+-------------+
| Cat_1         | Pass        |
| Cat_1         | N/A         |
| Cat_2         | Fail        |
| Cat_2         | Fail        |
| Cat_3         | Pass        |
| Cat_3         | Pass        |
| Cat_3         | Fail        |
| Cat_3         | N/A         |
+---------------+-------------+

我需要这样一张桌子:

+------+------+------+-----+
|      | Pass | Fail | N/A |
+------+------+------+-----+
| Cat1 |    1 |      |   1 |
| Cat2 |      |    2 |     |
| Cat3 |    2 |    1 |   1 |
+------+------+------+-----+

我尝试使用Pivot,但无法弄清楚如何使它从Test_Result列计数出现次数并将它们作为值放入pivot结果中。

谢谢!

python pandas pivot
2个回答
1
投票

这里有问题qazxsw poi值被排除在外,所以必须使用qazxsw poi与NaN

fillna

或者使用crosstabdf1 = pd.crosstab(df['Test_Category'], df['Test_Result'].fillna('n/a')) print (df1) Test_Result Fail Pass n/a Test_Category Cat_1 0 1 1 Cat_2 2 0 0 Cat_3 1 2 1 进行重塑:

GroupBy.size

unstack

df['Test_Result'] = df['Test_Result'].fillna('n/a') df1 = df.groupby(['Test_Category','Test_Result']).size().unstack() print (df1) Test_Result Fail Pass n/a Test_Category Cat_1 NaN 1.0 1.0 Cat_2 2.0 NaN NaN Cat_3 1.0 2.0 1.0 的另一个解决方案:

df1 = df.groupby(['Test_Category','Test_Result']).size().unstack(fill_value=0)
print (df1)
Test_Result    Fail  Pass  n/a
Test_Category                 
Cat_1             0     1    1
Cat_2             2     0    0
Cat_3             1     2    1

1
投票

你可以使用两列中的唯一值作为索引和列来构造一个新的数据帧,并使用pandas'pivot_table

df = df.pivot_table(index='Test_Category',columns='Test_Result', aggfunc='size')

输出:

iterrows()

虽然使用df_out = pd.DataFrame(index=df['Test_Category'].unique().tolist(), columns=df['Test_Result'].unique().tolist()) for index, row in df_out.iterrows(): for col in df_out.columns: df_out.loc[index, col] = len(df[(df['Test_Category'] == index) & (df['Test_Result'] == col)]) 肯定会更快。

© www.soinside.com 2019 - 2024. All rights reserved.