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

时间:2019-09-20 07:16:47

标签: 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]

但这根本没有任何结果。有人可以帮我吗?如何获得理想的结果?

非常感谢您

1 个答案:

答案 0 :(得分:1)

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

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  <label>Points 1</label> <input id="points1" type="text">
</div>
<div>
  <label>Points 2</label> <input id="points2" type="text">
</div>
<div>
  <label>Name</label> <input id="name1" type="text">
</div>

然后使用DataFrame.ilocIndex.get_loc进行选择来重新分配值

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

或通过索引将DataFrame.loc用于选择索引值:

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