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

标签 python python-3.x pandas dataframe

我有以下数据框:

                                   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/

相关文章:

python - 替换 N-d numpy 数组中的字符串

python-3.x - 通过python进行 Elasticsearch 时计数错误

python - 取决于行号的函数

python - 如何将以下数据框转换为多索引数据框?

python - 嵌套查询/在 Pandas 中有效地比较多个数据集

python - 在TensorFlow中评估CIFAR-10时如何获得类别概率?

python MySQL连接器

python - 合并多个 KML 文件

python-3.x - python中的resample或asfreq pandas时间序列数据帧错误为 'Duplicate Index'

python - 在 Ubuntu 机器上安装 Python3.7,dist-packages 为空