gpt4 book ai didi

python - 如何按行将值从一列移动到另一列?

转载 作者:行者123 更新时间:2023-12-01 07:14:59 24 4
gpt4 key购买 nike

我有以下数据框:

                                   preference                     Other
588 NaN goes to work with sister
461 NaN google
88 NaN bybus, mobike
44 NaN TMB
141 NaN Smou
741 NaN Scoot
90 NaN SDFASDAF
612 NaN Reby (electric scooter)
217 NaN Moovit
453 NaN Leasing
427 NaN Leasing
162 NaN LEASING
247 NaN JUSTMOOVE
459 NaN Free now
131 NaN Drivy
510 NaN Car2go
185 NaN Cabify
742 NaN Cabify
557 NaN public transport
0 No app NaN
1 NaN NaN
2 No app NaN
3 No app NaN

我只想将前 19 个值从 Other 列移至 preference 列。该数据帧是较大数据帧的子集,并按 Other 列按降序排序以获得此结果。

我已经尝试过这个:

df[["preference", "Other"]].sort_values(by = "Other",  ascending = False)["preference"].iloc[0:19] = df["Other"].sort_values( ascending = False).iloc[0:19]

但这根本没有返回任何结果。有人可以帮我解决这个问题吗?我怎样才能得到想要的结果?

提前非常感谢

最佳答案

您可以先排序并分配给原始:

df = df.sort_values(by = "Other",  ascending = False)

然后通过 DataFrame.iloc 选择来重新分配值与 Index.get_loc

df.iloc[0:19, df.columns.get_loc("preference")] = df.iloc[0:19, df.columns.get_loc("Other")]

或者使用DataFrame.loc通过索引选择索引值:

df.loc[df.index[0:19], "preference"] = df.loc[df.index[0:19], "Other"]

关于python - 如何按行将值从一列移动到另一列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58023526/

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