python - 如何嵌套 numpy() 的 np.where,或者一个接一个?

标签 python python-3.x pandas numpy dataframe

我有一个数据框,我需要根据特定条件在其中添加一列。我成功地做到了这一点(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/

相关文章:

python-3.x - aiohttp client_exception ServerDisconnectedError - 这是 API 服务器的问题还是 aiohttp 或我的代码?

java - Python 服务器打印 ASCII 而不是整数

python - pandas 将零替换为其他列中的下一个值

python - pandas - 根据数据框分组创建键值对

python - 尝试从多个帧创建视频

python itertools 向前跳过

python MySQL : how do loop through table and regex-replacing field?

python-3.x - 将matplotlib图表直接导出到Excel?不先保存到文件

python - 导出动画 ffmpeg 时出错 - Matplotlib

Pandas get dummies() 来获取数字分类数据