我的DataFrame看起来像这样:
a b c d e f g
0 x y 1 3 4 5 6
1 x y -1 7 8 5 6
2 x y -1 7 8 3 4
对于df.c == -1
的行,我希望按升序对df.d
和df.g
之间的所有列进行排序。
结果将是:
a b c d e f g
0 x y 1 3 4 5 6
1 x y -1 5 6 7 8
2 x y -1 3 4 7 8
我尝试了几件事,但似乎都没有效果:
for row in df.itertuples():
if row.c == -1:
subset = row[4:]
sorted = sorted(subset)
df.replace(to_replace=subset, value= sorted)
以及
df.loc[df.c == -1, df[4:]] = sorted(df[4:])
答案 0 :(得分:3)
您可以在感兴趣的区域使用numpy.sort
。
mask = df.c.eq(-1), slice('d', 'g')
df.loc[mask] = np.sort(df.loc[mask].values)
df
# a b c d e f g
# 0 x y 1 3 4 5 6
# 1 x y -1 5 6 7 8
# 2 x y -1 3 4 7 8
答案 1 :(得分:1)
可能不是最快的,但这有效:
rmask = df.c == -1
cmask = ['d', 'e', 'f', 'g']
df.loc[rmask, cmask] = df.loc[rmask, cmask].apply(lambda row: sorted(row), axis=1)
df
a b c d e f g
0 x y 1 3 4 5 6
1 x y -1 5 6 7 8
2 x y -1 3 4 7 8