首页 > 解决方案 > 添加一个新列,其中一些值被操作

问题描述

我有一个数据框,其中 1 列用日期填充,第 2 列用年龄填充。我想添加第三列,它查看 Ages 列,如果行中的值 < 20,则将其乘以 2,否则只需将 Age 放在该行中。下面的 lambda 函数将每个 Age 乘以 2。


def fun(df):
    change = df.loc[:, "AGE"].apply(lambda x: x * 2 if x <20 else x)
    df.insert(2, "NEW_AGE", change)

    return df



标签: pythonpandas

解决方案


使用pandas.Series.where

import pandas as pd
import numpy as np

df = pd.DataFrame(np.arange(15, 25), columns=['AGE'])
df['AGE'].where(df['AGE'] >= 20, df['AGE'] * 2)

输出:

0    30
1    32
2    34
3    36
4    38
5    20
6    21
7    22
8    23
9    24
Name: AGE, dtype: int64

推荐阅读