python - 添加一个新列,其中一些值被操作
问题描述
我有一个数据框,其中 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
解决方案
使用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
推荐阅读
- vb.net - System.Data.OleDb.OleDbException:“INSERT INTO 语句中的语法错误。”
- jquery - 使用 jQuery 更改 iframe
- html - 用Mozilla浏览器控件替换VS2019中的WebBrowser控件(v1.7.12)
- java - 如何使用 Java 8 groupingBy 收集到不同类型的列表中?
- rust - 是否可以仅为发布模式调用 build.rs?
- java - 连接到 localhost 时出现连接错误
- maven - maven build in github 持续集成动作
- python - 如何创建模块列表列表
- python-3.x - 通过 selenium Python 从网站的下拉列表中选择值
- sql - 解析代码库中嵌入的 SQL