在前 4 个字符后按字母顺序按列对 pandas 数据帧进行排序
sorting pandas dataframe by column alphabetically after first 4 characters
我有一个这样的数据框
new_col new_elements new_val old_col old_elements old_val
0 0 384444683 593 2 423483819 480
1 1 384444684 594 32 248239340 341
2 2 384444686 596 0 249289049 342
我想要这个:
new_col old_col new_elements old_elements new_val old_val
0 0 2 384444683 423483819 593 480
1 1 32 384444684 248239340 594 341
2 2 0 384444686 249289049 596 342
我知道 df.sort_index(axis=1)
会按字母顺序对我的专栏进行排序,但它们现在已经按这种方式排序了。我想要的是在前缀(前 4 个字符)
之后按字母顺序对它们进行排序
我不是专家,但我会这样做:
fields = ['new_col', 'old_col', 'new_elements', 'old_elements', 'new_val', 'old_val']
df = df[fields]
col = df.columns
col = sorted(col,key=lambda x: x[4:])
col
df = df[col]
df
一共df = df[sorted(df.columns,key=lambda x: x[4:])]
您也可以sort_index
提供密钥:
df.sort_index(axis=1, key=lambda s: s.str[4:])
new_col old_col new_elements old_elements new_val old_val
0 0 2 384444683 423483819 593 480
1 1 32 384444684 248239340 594 341
2 2 0 384444686 249289049 596 342
我有一个这样的数据框
new_col new_elements new_val old_col old_elements old_val
0 0 384444683 593 2 423483819 480
1 1 384444684 594 32 248239340 341
2 2 384444686 596 0 249289049 342
我想要这个:
new_col old_col new_elements old_elements new_val old_val
0 0 2 384444683 423483819 593 480
1 1 32 384444684 248239340 594 341
2 2 0 384444686 249289049 596 342
我知道 df.sort_index(axis=1)
会按字母顺序对我的专栏进行排序,但它们现在已经按这种方式排序了。我想要的是在前缀(前 4 个字符)
我不是专家,但我会这样做:
fields = ['new_col', 'old_col', 'new_elements', 'old_elements', 'new_val', 'old_val']
df = df[fields]
col = df.columns
col = sorted(col,key=lambda x: x[4:])
col
df = df[col]
df
一共df = df[sorted(df.columns,key=lambda x: x[4:])]
您也可以sort_index
提供密钥:
df.sort_index(axis=1, key=lambda s: s.str[4:])
new_col old_col new_elements old_elements new_val old_val
0 0 2 384444683 423483819 593 480
1 1 32 384444684 248239340 594 341
2 2 0 384444686 249289049 596 342