Python 熊猫:反转具有相同值的行
我有一个Python 熊猫:反转具有相同值的行,python,pandas,dataframe,Python,Pandas,Dataframe,我有一个DataFrame,其中行由第三列“分组”(一个“组”中的行在第三列具有相同的值): 但第二列中的值顺序错误。我需要反转每个“组”中的行,因此DataFrame应该如下所示: c1 c2 c3 0 r 1 1 b 1 2 n 2 3 x 2 4 f 2 5 f 3 6 r 3 是否有有效的方法将第一个数据帧转换为第二个数据帧 UPD:更新了更清晰的示例。这些值应该完全颠倒,而不仅仅是按字母顺序排列。您似乎需要: 编辑: 您可以使用groupby
DataFrame
,其中行由第三列“分组”(一个“组”中的行在第三列具有相同的值):
但第二列中的值顺序错误。我需要反转每个“组”中的行,因此DataFrame
应该如下所示:
c1 c2 c3
0 r 1
1 b 1
2 n 2
3 x 2
4 f 2
5 f 3
6 r 3
是否有有效的方法将第一个数据帧
转换为第二个数据帧
UPD:更新了更清晰的示例。这些值应该完全颠倒,而不仅仅是按字母顺序排列。您似乎需要:
编辑:
您可以使用groupby
并通过[::-1]
更改订单:
#more general solution, working with not unique index also
def reversing(x):
x['c2'] = x['c2'].iloc[::-1].values
return x
df = df.groupby('c3', sort=False)).apply(reversing)
print (df)
c1 c2 c3
0 0 r 1
1 1 b 1
2 2 n 2
3 3 x 2
4 4 f 2
5 5 f 3
6 6 r 3
#solution working only with unique monotonic increasing index, because reset index
df['c2'] = df.groupby('c3', sort=False)['c2'].apply(lambda x: x[::-1]).reset_index(drop=True)
print (df)
c1 c2 c3
0 0 r 1
1 1 b 1
2 2 n 2
3 3 x 2
4 4 f 2
5 5 f 3
6 6 r 3
解决方案,c1
中的值顺序发生变化:
您可以按索引排序(必须是唯一的单调递增)
如果列c1
是唯一的单调递增(0,1,2..)作为默认索引:
df = df.sort_values(['c3','c1'], ascending=[True, False])
print (df)
c1 c2 c3
1 1 r 1
0 0 b 1
4 4 n 2
3 3 x 2
2 2 f 2
6 6 f 3
5 5 r 3
谢谢你的回答,但这些字母只是价值观的一个例子,很抱歉我错误地引用了这个例子。在我的例子中,组中的值不应该按字母顺序排列,它们应该完全颠倒。我已经用更清晰的例子更新了这篇文章。
#more general solution, working with not unique index also
def reversing(x):
x['c2'] = x['c2'].iloc[::-1].values
return x
df = df.groupby('c3', sort=False)).apply(reversing)
print (df)
c1 c2 c3
0 0 r 1
1 1 b 1
2 2 n 2
3 3 x 2
4 4 f 2
5 5 f 3
6 6 r 3
#solution working only with unique monotonic increasing index, because reset index
df['c2'] = df.groupby('c3', sort=False)['c2'].apply(lambda x: x[::-1]).reset_index(drop=True)
print (df)
c1 c2 c3
0 0 r 1
1 1 b 1
2 2 n 2
3 3 x 2
4 4 f 2
5 5 f 3
6 6 r 3
df=df.reset_index().sort_values(['c3','index'],ascending=[True, False]).drop('index',axis=1)
print (df)
c1 c2 c3
1 1 r 1
0 0 b 1
4 4 n 2
3 3 x 2
2 2 f 2
6 6 f 3
5 5 r 3
df = df.sort_values(['c3','c1'], ascending=[True, False])
print (df)
c1 c2 c3
1 1 r 1
0 0 b 1
4 4 n 2
3 3 x 2
2 2 f 2
6 6 f 3
5 5 r 3