python - 仅将函数应用于 Pandas Dataframe 列的一部分

标签 python pandas

我有一个如下所示的数据框:

Date        Last
2016-11-03  101.58  
2016-11-04  100.50  
2016-11-07  103.55  
2016-11-08  104.63  
2016-11-09  106.15  
2016-11-10  107.65  
2016-11-11  106.74  
2016-11-14  108.22  
2016-11-15  107.92  
2016-11-16  106.03  

和一个简单的函数:

def new_def(x):
    add=70.00
    return x[0]+add

我想使用该函数向数据框添加另一列,但我只想将其应用于“2016-11-09”之前的日期。我试过这样做:

df['New']= df[:'2016-11-09'].apply(new_def, axis=1)

结果列在“2016-11-09”之前都是正确的,之后是 NaN。关于如何在 '2016-11-09' 之前返回 'x[0] + add' 和之后返回 'x[0]' 有什么建议吗?

提前致谢

最佳答案

您可以重写您的 new_def 函数以获取日期参数:

def new_def(val, date):
    return val+70.0 if date < pd.datetime(2016, 11, 9) else val

然后像这样应用它:

df.apply(lambda r: newdef(r['Last'], r.name), 1)

关于python - 仅将函数应用于 Pandas Dataframe 列的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40784621/

相关文章:

python - 构建用于牛眼皮疹识别的卷积神经网络

python - 安装 python-telegram-bot 时出现错误 "No package ' libffi' found

python - python 3 TypeError : '>' not supported between instances of 'int' and 'str' in an if statment

python - 根据Python中的其他列生成自定义ID

python - 如何过滤 Pandas 中的分类数据

python - 使用 pandas groupby 时 csv 中的列出现问题

python - Pyramid :设置内容类型以响应匹配接受 header ?

python - 匹配两个打印中的相同单词

python - 在一张图中绘制多个时间序列

pandas - 重复实验并将结果存储在数据框中