检查 Pandas 系列中的最大值,其中该系列包含具有数值的字母

Checking for maximum value in a Pandas series, where the series contains letters that have numeric value

我有一个包含 6 列的 pandas 数据框,每列给出一个 'status'。这些状态可以是以下任何一种:T, N, 0, U, D, 1, 2, 3, 4, 5, 6, 8。 其中为了比较,T > N > 0 > U > D > 1 > 2...

我想要实现的是创建一个新列,WORST STATUS,它可以从这个列表中挑选出最大值(类似于 df.max(),其中 max 方法可以识别"U" 大于 0。

我知道我可能可以将所有这些包含在 if-else 中并进行元素方面的比较,但我想知道是否还有更“干净”的东西?

您可以使用 ordered Categorical,因此可以使用 max 函数:

df = pd.DataFrame(data={'col':[1, 2, 3, 4, 'N', 'N', 0, 'U', 'D', 5, 6, 8]})

cats = ['T', 'N', 0, 'U', 'D', 1, 2, 3, 4, 5, 6, 8]
df['col'] = pd.Categorical(df['col'], ordered=True, categories=cats[::-1])

print (df['col'])
Categories (12, object): [8 < 6 < 5 < 4 ... 'U' < 0 < 'N' < 'T']

#in data is no T, so N is maximal
print (df['col'].max())
N

如果需要处理多列:

cols = ['col1','col2','col3']
df[cols] = df[cols].apply(lambda x: pd.Categorical(x, ordered=True, categories=cats[::-1]))

然后:

print (df[cols].max(axis=1))