【问题标题】:python reorder a column and the dataframe in a desired orderpython以所需的顺序重新排序列和数据框
【发布时间】:2021-08-23 11:53:29
【问题描述】:
我有一个带有重复字符串值的数据框。我想按所需的顺序重新排序。
我的代码:
df =
name
0 Fix
1 1Ax
2 2Ax
3 2Ax
4 1Ax
5 Fix
df.sort_values(by=['name'],ignore_index=True,ascending=False))
print(df)
df =
name
0 Fix
1 Fix
2 2Ax
3 2Ax
4 1Ax
5 1Ax
预期答案:
df =
name
0 Fix
1 Fix
2 1Ax
3 1Ax
4 2Ax
5 2Ax
【问题讨论】:
标签:
python
pandas
dataframe
sorting
【解决方案1】:
目前您正在按字母倒序排序:因此“F”在“2”之前,“2”在“1”之前。将 ascending 更改为 True 将在底部放置“修复”。
这有点小技巧,但您可以将第一个字符为数字的行拉出来,分别对它们进行排序...
import pandas as pd
df = pd.DataFrame(['Fix', '1Ax','2Ax','2Ax','1Ax','Fix'], columns=['name'])
# Sort alphabetically
df = df.sort_values(by=['name'],ignore_index=True,ascending=True)
# Get first character of string
first_digit = df['name'].str[0]
# Get cases where first character is (not) a number
starts_with_digits = df[first_digit.str.isdigit()]
not_starts_with_digits = df[~first_digit.str.isdigit()]
# Switch order of row with first character which start with number/not a number
pd.concat([not_starts_with_digits, starts_with_digits]).reset_index(drop=True)