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

2024-10-01 07:40:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下数据帧:

                                   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]

但这根本没有结果。有人能帮我吗?我怎样才能得到想要的结果

事先非常感谢


Tags: 数据nofalseappdfnansortvalues
1条回答
网友
1楼 · 发布于 2024-10-01 07:40:00

您可以先对原始文件进行排序和分配:

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

然后通过选择^{}^{}重新分配值

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

或使用^{}通过索引选择索引值:

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

相关问题 更多 >