我有一个包含 2 列有序分类数据(相同类别)的 DataFrame。我想构建另一列,其中包含前 2 列的分类最大值。我设置了以下。
import pandas as pd
from pandas.api.types import CategoricalDtype
import numpy as np
cats = CategoricalDtype(categories=['small', 'normal', 'large'], ordered=True)
data = {
'A': ['normal', 'small', 'normal', 'large', np.nan],
'B': ['small', 'normal', 'large', np.nan, 'small'],
'desired max(A,B)': ['normal', 'normal', 'large', 'large', 'small']
}
df = pd.DataFrame(data).astype(cats)
尽管 np.nan 项有问题,但可以比较列,如运行以下代码所示。
df['A'] > df['B']
该手册建议 max() 适用于分类数据,因此我尝试按如下方式定义我的新列。
df[['A', 'B']].max(axis=1)
这会产生一列 NaN。为什么?