Python 对符合条件的行的列子集进行排序
我的数据框如下所示:Python 对符合条件的行的列子集进行排序,python,python-3.x,pandas,dataframe,rows,Python,Python 3.x,Pandas,Dataframe,Rows,我的数据框如下所示: 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.
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:])
可能不是最快的,但这很有效:
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
可能不是最快的,但这很有效:
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
您可以在感兴趣的区域上使用
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
您可以在感兴趣的区域上使用
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
我不想在排序时“移动”列标签。我需要它们保持原样,但必须对值进行排序。对不起,我不太清楚。如果您需要更多信息,请告诉我!编辑:c=-1我需要行保持不变,可能是保持在它们所在的位置,但是如果它们被移动到顶部或底部,这没有多大关系,我仍然可以在之后根据df.a进行排序。没有意义。我以为您想对行进行排序,但意识到您需要对列进行排序。我不想在排序时“移动”列标签。我需要它们保持原样,但必须对值进行排序。对不起,我不太清楚。如果您需要更多信息,请告诉我!编辑:c=-1我需要行保持不变,可能是保持在它们所在的位置,但是如果它们被移动到顶部或底部,这没有多大关系,我仍然可以在之后根据df.a进行排序。没有意义。我以为您想对行进行排序,但意识到您需要对列进行排序。非常感谢,它工作得非常好,效率也非常高!非常感谢,它工作得非常好,非常有效!