熊猫枢轴重复条目

时间:2020-10-22 09:26:01

标签: python pandas

我正在尝试转换此数据框:

| project  | id | problem | result |
|----------|----|---------|--------|
| Project1 | 1  | P1      | True   |
| Project1 | 1  | P2      | True   |
| Project1 | 1  | P3      | False  |
| Project1 | 1  | P4      | True   |
| Project1 | 1  | P5      | NA     |
| Project2 | 1  | P1      | True   |
| Project2 | 1  | P2      | False  |
| Project2 | 1  | P3      | False  |
| Project2 | 1  | P4      | NA     |
| Project2 | 1  | P5      | True   |

对此:

| project  | id | P1   | P2    | P3    | P4   | P5   |
|----------|----|------|-------|-------|------|------|
| Project1 | 1  | True | True  | False | True | NA   |
| Project2 | 1  | True | False | False | NA   | True |

我尝试了数据透视方法:

df.pivot(index=["project", "id"], columns="problem", values="result")

但是,我得到了错误:ValueError: Index contains duplicate entries, cannot reshape

如何转换数据框?

1 个答案:

答案 0 :(得分:2)

DataFrame.pivot_table与自定义lambda函数一起使用:

df = df.pivot_table(index=["project", "id"], 
                    columns="problem", 
                    values="result", 
                    aggfunc=lambda x: x.any() if x.notna().all() else np.nan)
print (df)
problem        P1     P2     P3    P4    P5
project  id                                
Project1 1   True   True  False  True   NaN
Project2 1   True  False  False   NaN  True

如果需要使用NaN和布尔值True/False,可以使用Nullable Boolean data type

df['result'] = df['result'].astype('boolean')

df = df.pivot_table(index=["project", "id"], 
                    columns="problem",
                    values="result", 
                    aggfunc=lambda x: x.any() if x.notna().all() else np.nan)
print (df)
problem        P1     P2     P3    P4    P5
project  id                                
Project1 1   True   True  False  True  <NA>
Project2 1   True  False  False  <NA>  True

如果可能,仅输出True/False

df = df.pivot_table(index=["project", "id"], 
                    columns="problem",
                    values="result", 
                    aggfunc='any')
print (df)
problem        P1     P2     P3     P4     P5
project  id                                  
Project1 1   True   True  False   True  False
Project2 1   True  False  False  False   True