Сортировка pandas столбца по номеру в суффиксе после подчеркивания - PullRequest
1 голос
/ 07 мая 2020

У меня есть Dataframe со следующим набором столбцов:

bill_id, product_1, product_20, product_300, price_1, price_20, price_300, quantity_1, quantity_20, quantity_300

Я бы хотел, чтобы это было отсортировано в приведенной ниже последовательности на основе числа после подчеркивания в конце каждой метки столбца

bill_id, product_1, price_1, quantity_1, product_20, price_20, quantity_20, product_300, price_300, quantity_300

1 Ответ

2 голосов
/ 07 мая 2020

Используйте sorted с лямбда-функцией по номеру после _ во всех столбцах без первого, а затем измените порядок на DataFrame.reindex:

c = 'bill_id, product_1, product_20, product_300, price_1, price_20, price_300, quantity_1, quantity_20, quantity_300'

df = pd.DataFrame(columns=c.split(', '))
print (df)
Empty DataFrame
Columns: [bill_id, product_1, product_20, product_300, 
          price_1, price_20, price_300, quantity_1, quantity_20, quantity_300]
Index: []

c = sorted(df.columns[1:], key=lambda x: int(x.split('_')[-1]))
print (c)
['product_1', 'price_1', 'quantity_1', 
 'product_20', 'price_20', 'quantity_20', 
 'product_300', 'price_300', 'quantity_300']

df = df.reindex(df.columns[:1].tolist() + c, axis=1)
print (df)
Columns: [bill_id, product_1, price_1, quantity_1, 
         product_20, price_20, quantity_20, 
         product_300, price_300, quantity_300]
Index: []

Другая идея - создать индекс по всем столбцам, отличным от продукта, и отсортировать по всем столбцам:

df = df.set_index('bill_id')
c = sorted(df.columns, key=lambda x: int(x.split('_')[-1]))

df = df.reindex(c, axis=1)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...