python - 交换某些行中的列

标签 python pandas dataframe

我有这样的 DataFrame:

     A            B      C
"010-1"       "Car"     500
"010-2"     "Train"     302
"Result"      "010"      23
"011-1"      "Ship"     321
"011-2"     "Plane"     321
"011-3"      "Bike"     321
"Result"      "011"     321

现在可以在 "Result"A< 中的行中移动 AB 使用 Pandas ?

所以最终结果是:

     A            B       C
"010-1"       "Car"     500
"010-2"     "Train"     302
  "010"     "Result"     23
"011-1"      "Ship"     321
"011-2"     "Plane"     321
"011-3"      "Bike"     321
  "011"    "Result"     321

编辑:实际上,除了 A 和 B 之外,可能还有不止一列

最佳答案

你可以使用 numpy 函数 where():

原始数据框:

In[6]: df
Out[6]: 
        A      B    C
0   010-1    Car  500
1   010-2  Train  302
2  Result    010   23
3   011-1   Ship  321
4   011-2  Plane  321
5   011-3   Bike  321
6  Result    011  321

命令:
(使用常见的 Python 模式 x, y = y, x 来切换值)

In[7]: cond = df.A == "Result"
In[8]: df.A, df.B = np.where(cond, df.B, df.A), np.where(cond, df.A, df.B)

结果:

In[9]: df
Out[9]: 
       A       B    C
0  010-1     Car  500
1  010-2   Train  302
2    010  Result   23
3  011-1    Ship  321
4  011-2   Plane  321
5  011-3    Bike  321
6    011  Result  321

关于python - 交换某些行中的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61952863/

相关文章:

python - Django - 开放时间表单集

python - 如何将Python pandas数据保存到Excel文件中?

python - 如何通过跳过 DataFrame 中的不可用日期来获取下面 Python DataFrame 的三天最高价、最低价和收盘价?

python - Pandas 删除列表中除最后一项之外的所有项目

python - 如何检查DataFrame的列是否包含float类型?

python - 连接使用循环生成的 pandas DataFrame

python - 如何在 OpenCV/python 上更改轮廓颜色

python - 将数据框重新组织为多索引

python - Tensorflow 没有正确安装

python - 带有来自 Pandas DataFrame 的数据的 Spacy NLP