gpt4 book ai didi

python - Pandas 中的列成对重组

转载 作者:行者123 更新时间:2023-12-03 20:25:55 24 4
gpt4 key购买 nike

我有这样的数据

df = pd.DataFrame([[2,1,3,3],[2,3,2,4],[4,1,3,2]],columns=['A1','A2','B1','B2'])

df
A1 A2 B1 B2
0 A:2 A:1 B:3 B:3
1 A:2 A:3 B:2 B:4
2 A:4 A:1 B:3 B:2

A1、A2中的值为一对,与B1、B2相同。

现在我想重新组织每一对,使它们按字母顺序排列:
df
A1 A2 B1 B2
0 A:1 A:2 B:3 B:3
1 A:2 A:3 B:2 B:4
2 A:1 A:4 B:2 B:3

我可以用 for 做到这一点对每一对循环,排序,然后将其重新解析为 Pandas 框架:
for index, row_ in df.iterrows():
for pair_ in range(int(len(row_)/2)):
print(index, pair_)
pair = row_[pair_*2:(pair_*2+2)]
df.iloc[index, pair_*2:(pair_*2+2)] = pair.sort_values()

但这似乎非常低效。

请建议我更好的方法,谢谢

最佳答案

您可以简单地取 2 列的最小值和最大值,然后重新分配它们:

pairs = (('A1', 'A2'), ('B1', 'B2'))  # or any other way to define the pairs

for c1, c2 in pairs:
df[c1], df[c2] = np.minimum(df[c1], df[c2]), np.maximum(df[c1], df[c2])

关于python - Pandas 中的列成对重组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61160387/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com