按第二行顺序对pandas dataframe列进行排序

bweufnob  于 2023-06-04  发布在  其他
关注(0)|答案(3)|浏览(200)

我需要根据第二行的顺序对 Dataframe 进行排序。例如:

import pandas as pd

data = {'1a': ['C', 3, 1], '2b': ['B', 2, 3], '3c': ['A', 5, 2]}
df = pd.DataFrame(data)
df

输出:

1a 2b 3c
0  C  B  A
1  3  2  5
2  1  3  2

所需输出:

3c 2b 1a
0  A  B  C
1  5  2  3
2  2  3  1

因此,这些列已经基于零索引行,基于A、B、C进行了排序。
尝试了许多排序选项,但没有成功。
有一种快速的方式来完成这一点将是有益的,但是有粒度控制来对元素进行排序并将特定列移动到第一位置将更好。例如,将“C”移动到第一列。
比如做一个列表,排序,移动和重新排序列表。

mylist = ['B', 'A', 'C']
mylist.sort()
mylist.insert(0, mylist.pop(mylist.index('C')))

然后对 Dataframe 进行排序['C','A','B']输出

1a 3c 2b
0  C  A  B
1  3  5  2
2  1  2  3
t1qtbnec

t1qtbnec1#

您可以尝试:

df = df[df.iloc[0].sort_values().index]

退货:

3c 2b 1a
0  A  B  C
1  5  2  3
2  2  3  1

在本例中,您使用的是第一行,并对它进行排序,然后返回排序后的索引值。你有很大的灵活性,你甚至可以按多列/行排序,这种方式也。

svmlkihl

svmlkihl2#

如果要将特定列移动到第一个位置,可以修改代码,如示例所示:

import pandas as pd

data = {"1a": ["C", 3, 1],
        "2b": ["B", 2, 3],
        "3c": ["A", 5, 2]}
df = pd.DataFrame(data)
print(df)
#   1a 2b 3c
# 0  C  B  A
# 1  3  2  5
# 2  1  3  2

# Get the second row and convert it to a list
second_row = df.iloc[1, :].tolist()
print(second_row)
# [3, 2, 5]

# Define the column you want to move to the first position
target_column = "1a"

# Sort the list
sorted_columns = sorted(range(len(second_row)), key=lambda k: second_row[k])
print(sorted_columns)

# Move the target column to the first position
sorted_columns.remove(df.columns.get_loc(target_column))
sorted_columns.insert(0, df.columns.get_loc(target_column))

# Reorder the columns of the DataFrame based on the sorted list
df = df.iloc[:, sorted_columns]

print(df)
#   1a 2b 3c
# 0  C  B  A
# 1  3  2  5
# 2  1  3  2
dxpyg8gm

dxpyg8gm3#

在Pyjedy和Stingher的帮助下,我能够解决这个问题。其中一个问题是由于我的输入。输入由列表而不是字典组成,所以我需要转换它。因此,我有行的索引和列的索引。因此,从列表中选择元素需要获得索引。

import pandas as pd

def search_list_for_pattern(lst, pattern):
    for idx, item in enumerate(lst):
        if pattern in item:
            break
    return idx

data = [['1a', 'B', 2, 3], ['2b', 'C', 3, 1], ['3c', 'A', 5, 2]]
df = pd.DataFrame(data).transpose()
print(df)

#     0   1   2
# 0  1a  2b  3c
# 1   B   C   A
# 2   2   3   5
# 3   3   1   2

# Get the second row and convert it to a list
second_row = df.iloc[1, :].tolist()
print(second_row)

# ['B', 'C', 'A']

# Find the index of the column you want to move to the first position
target_column = search_list_for_pattern(second_row, "C")
print(target_column)

# 1

# Sort the list
sorted_columns = sorted(range(len(second_row)), key=lambda k: second_row[k])
print(sorted_columns)

# [2, 0, 1]

# Move the target column to the first position
sorted_columns.remove(df.columns.get_loc(target_column))
sorted_columns.insert(0, df.columns.get_loc(target_column))

# Reorder the columns of the DataFrame based on the sorted list
df = df.iloc[:, sorted_columns]
print(df)

#     1   2   0
# 0  2b  3c  1a
# 1   C   A   B
# 2   3   5   2
# 3   1   2   3

df.to_excel('ordered.xlsx', sheet_name='Sheet1', index=False, header=False)

相关问题