Используйте 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)