微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Pandas 按两列分组,在其他 4 列中交换值

如何解决Pandas 按两列分组,在其他 4 列中交换值

我有一个包含许多列的大型 Pandas DataFrame。我想确保 C 列和 E 列包含相同顺序的值。

例如:如果 first two rows shows (red and green) & third row shows (Green and red)third row should change it to red and green 如下所示。

输入

enter image description here

输出

enter image description here

附加任务:

在进行此更改时,我想交换同一行中其他四列(2 对)的值。

输入

enter image description here

输出

enter image description here

注意:当我们应用 group by 时,它也包括下面突出显示的行,但我不想交换值,因为它有一个标准序列,先红后绿。

enter image description here

我已经尝试过使用以下功能,但是在输入了 100 条之后,很难手动跟踪所有组合。文件很大,有很多行和列。

def swap(x):
    if x[0] < 0:
        return [x[1],x[0]]
    else:
        return [x[0],x[1]]

有没有办法在给定条件下交换多个值?

编辑 1:在 Rob Raymond 的回答之后

import pandas as pd
import itertools
import random

df = pd.read_excel("Path\\test_copy.xlsx") # My original excel sheet which contains all data  

colors1 = []
colors2 = []
colors = []
colors1 = df['C'].values.tolist()
colors2 = df['E'].values.tolist()
colors = colors1 + colors2
colors = list( dict.fromkeys(colors) )
colorp = list(itertools.permutations(colors,2))

df1 = pd.DataFrame([pd.Series(colorp[random.randint(0,len(colorp)-1)]).rename({0:"C",1:"E"}).to_dict() for i in range(20)])

# find rows where colors in different order to a prevIoUs combination
df2 = df.assign(swap=df.apply(lambda r: ((df.loc[(df.C.eq(r.E)&df.E.eq(r.C))].index.values)<r.name).any(),axis=1))

# swap the columns,can be extended to other columns
df2.loc[df2.swap] = df2.loc[df2.swap].rename(columns={"C":"E","E":"C"})
df2.loc[df2.swap] = df2.loc[df2.swap].rename(columns={"M":"N","M":"N"})
df2.loc[df2.swap] = df2.loc[df2.swap].rename(columns={"G":"I","I":"G"})


# lets compare what's happened...
df2.join(df,rsuffix="_start")

df2.to_excel (r"PAth\\result_swapped.xlsx",index = None,header=True)

值在所有六列中按预期同时交换,但结果不准确。输出文件opposite sequence 的“C”和“E”列中仍然包含一些值。对于那些 wrong sequence 行,交换状态为 “TRUE”。这意味着原始序列是正确的,但我们的脚本已经交换了它。

解决方法

  • 模拟您的数据
  • 模拟条件 - 较早的行与列的顺序相反
  • 交换列是使用掩码rename()
  • 完成的
import itertools
colors = ["Red","Green","Blue","Purple","Indigo","Pink"]

colorp = list(itertools.permutations(colors,2))

df = pd.DataFrame([pd.Series(colorp[random.randint(0,len(colorp)-1)]).rename({0:"C",1:"E"}).to_dict() for i in range(20)])

# find rows where colors in different order to a previous combination
df2 = df.assign(swap=df.apply(lambda r: ((df.loc[(df.C.eq(r.E)&df.E.eq(r.C))].index.values)<r.name).any(),axis=1))

# swap the columns,can be extended to other columns
df2.loc[df2.swap] = df2.loc[df2.swap].rename(columns={"C":"E","E":"C"})

# lets compare what's happened...
df2.join(df,rsuffix="_start")
C E 交换 C_start E_start
0 绿色 靛蓝 绿色 靛蓝
1 粉色 红色 粉色 红色
2 靛蓝 蓝色 靛蓝 蓝色
3 绿色 蓝色 绿色 蓝色
4 绿色 靛蓝 靛蓝 绿色
5 靛蓝 蓝色 蓝色 靛蓝
6 粉色 紫色 粉色 紫色
7 靛蓝 蓝色 蓝色 靛蓝
8 绿色 粉色 绿色 粉色
9 红色 蓝色 红色 蓝色
10 红色 靛蓝 红色 靛蓝
11 红色 紫色 红色 紫色
12 绿色 靛蓝 靛蓝 绿色
13 粉色 紫色 紫色 粉色
14 绿色 靛蓝 靛蓝 绿色
15 紫色 靛蓝 紫色 靛蓝
16 靛蓝 蓝色 蓝色 靛蓝
17 绿色 蓝色 绿色 蓝色
18 红色 绿色 红色 绿色
19 靛蓝 绿色 绿色 靛蓝

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?