我有一个Python Pandas Dataframe,其中名为status
的列包含三种可能的值:ok
,must read x more books
,does not read any books yet
,其中{{1} }是大于x
的整数。
我想根据上面的顺序对0
值进行排序。
示例:
status
我使用Pandas Categorical和map找到了一些有趣的提示,但我不知道如何处理修改字符串的变量值。
我该如何实现?
答案 0 :(得分:7)
使用:
a = df['status'].str.extract('(\d+)', expand=False).astype(float)
d = {'ok': a.max() + 1, 'does not read any book yet':-1}
df1 = df.iloc[(-df['status'].map(d).fillna(a)).argsort()]
print (df1)
name status
0 Paul ok
2 Robert must read 2 more books
1 Jean must read 1 more books
3 John does not read any book yet
说明:
答案 1 :(得分:2)
您可以将sorted
与自定义函数一起使用,以计算对数组进行排序的索引(非常类似于numpy.argsort
)。然后输入pd.DataFrame.iloc
:
df = pd.DataFrame({'name': ['Paul', 'Jean', 'Robert', 'John'],
'status': ['ok', 'must read 20 more books',
'must read 3 more books', 'does not read any book yet']})
def sort_key(x):
if x[1] == 'ok':
return -1
elif x[1] == 'does not read any book yet':
return np.inf
else:
return int(x[1].split()[2])
idx = [idx for idx, _ in sorted(enumerate(df['status']), key=sort_key)]
df = df.iloc[idx, :]
print(df)
name status
0 Paul ok
2 Robert must read 3 more books
1 Jean must read 20 more books
3 John does not read any book yet