基于键列和值列创建新列

时间:2019-09-23 11:09:17

标签: python pandas

我有两列键和值(继承了旧式错误的设计),我想根据键列并将该值用作行中的值,将该列分为多个其他列。

| Key                         | Value                       |
|-----------------------------|-----------------------------|
| .                           | None                        |
| Review Required?            | Yes                         |
| Installed?                  | No                          |
| Required Publish?           | No                          |
| Published?                  | Yes                         |
| Published?                  | No                          |
| Consult Required?           | Yes                         |
| IS Catalog Reference        | Null                        |
| License Review Required?    | No                          |

我尝试了类似的方法,但是没有用

  df.loc[~df['Key'].isnull()]
 .apply(lambda cols: pd.DataFrame({cols['Key']:cols['Value']},index=[1]),axis=0)

关于我希望得到的结果的样本:

| Review Required? | Installed?  | Required Publish? | Published?   | Published?  |
|------------------|-------------|-------------------|--------------|-------------|
|  Yes             | None        | None              | None         | None        |
| None             |          No | None              | None         | None        |
| None             | None        |  No               | None         | None        |
| None             | None        | None              |          Yes | None        |
| None             | None        | None              | None         |          No |

这种情况经常发生,不仅是是或否。 预先感谢。

1 个答案:

答案 0 :(得分:1)

使用DataFrame.dropna删除缺少值的行,将Key添加到索引并按Series.unstack进行重塑:

df = df.dropna(subset=['Key']).set_index('Key', append=True)['Value'].unstack()