我有一个数据框,我需要根据特定条件在其中添加一列。我成功地做到了这一点(How to have list's elements as a condition in np.where()?)。但是,当我两次应用相同的逻辑时,它不起作用。
我的数据框是:
period period_type
JAN16 month
JAN16 YTD
2017 2017
我想要的是:2017 年度
。
但是,我得到所有值的 annual
,即月、YTD 等更改为年度。
代码块:
def add_period_type(df):
months = ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC']
m = df.period.str.startswith(tuple(months))
df['period_type'] = np.where(m, 'month', df.period.str.split().str[0])
df.loc[~m, 'period'] = df.loc[~m, 'period'].str.split().str[1]
df["period"] = df["period"].combine_first(df["period_type"])
years = [str(x) for x in range(2000, 2100)]
y = df.period.str == (tuple(years))
print(y)
df['period_type'] = np.where(y, 'annual', df.period_type.str)
return df
前 3-4 行添加一个新列 period_type
。然后,我想根据上述条件稍微修改此列(检查该值是否为一年,如果是,则将年度分配给 period_type。相反,thbis 代码不起作用,它分配 annual
给所有人。
最佳答案
使用np.select()
:
str = """period
JAN16
YTD JAN16
2017"""
# sample dataframe
df = pd.read_csv(pd.io.common.StringIO(str))
months = ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC']
years = [ '{}'.format(x) for x in range(2000, 2100)]
# condition for month
m = df.period.str[:3].isin(months)
# condition for annual
y = df.period.isin(years)
# if contains spaces, then do JAN16, YTD
n = df.period.str.contains('\s')
df['period_type'] = np.select([m, y, n], ['month', 'annual', df.period.str.split().str[::-1].str.join(', ')])
df
# period period_type
#0 JAN16 month
#1 YTD JAN16 JAN16, YTD
#2 2017 annual
关于python - 如何嵌套 numpy() 的 np.where,或者一个接一个?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55961605/