熊猫系列 - >数据帧.从行创建列并使用零填充不匹配

Joh*_*ohn 4 python dataframe pandas

我有一个带有几列的pandas数据帧.然后我拉df [reason]并获得系列

some text 1                                          0.1178
Other string                                         0.0732
another string                                       0.0534

Name: reason, dtype: float64
Run Code Online (Sandbox Code Playgroud)

我想将其转换为数据框,看起来像:

                              some text 1    Other string another string
some text 1                   0.1178         0            0
Other string text             0              0.0732       0
another string here           0              0            0.0534
Run Code Online (Sandbox Code Playgroud)

如何将行复制为列并用0填充不匹配的行/列?

beh*_*uri 5

你可以使用np.diag:

>>> ts
some text 1       0.1178
Other string      0.0732
another string    0.0534
dtype: float64
>>> DataFrame(np.diag(ts), columns=ts.index, index=ts.index)
                some text 1  Other string  another string
some text 1          0.1178        0.0000          0.0000
Other string         0.0000        0.0732          0.0000
another string       0.0000        0.0000          0.0534
Run Code Online (Sandbox Code Playgroud)