gpt4 book ai didi

python - Pandas 系列 -> 数据框。从行创建列并用零填充不匹配项

转载 作者:太空狗 更新时间:2023-10-30 02:43:50 24 4
gpt4 key购买 nike

我有一个包含几列的 Pandas 数据框。然后我拉 df[reason] 并获得系列

some text 1                                          0.1178
Other string 0.0732
another string 0.0534

Name: reason, dtype: float64

我想将其转换成一个数据框,看起来像这样:

                              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

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

最佳答案

您可以使用 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

关于python - Pandas 系列 -> 数据框。从行创建列并用零填充不匹配项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31978196/

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