简体   繁体   English

Pandas Dataframe 从列中减去浮点值

[英]Pandas Dataframe subtracting float value from a column

Is there a way to subtract a constant value from the whole column?有没有办法从整列中减去一个常数值?

If my dataframe is如果我的数据框是

在此处输入图片说明

I want to subtract 2.5 from column 1 so that it appears as我想从第 1 列中减去 2.5,使其显示为

在此处输入图片说明

Also, is it possible to convert Date+Time into minutes?另外,是否可以将日期+时间转换为分钟?

Thank you!谢谢!

If df is your dataframe, simply use如果df是您的数据框,只需使用

df.Distance += 2.5

for adding a constant, or用于添加常数,或

df.Distance -= 2.5

for subtracting it.减去它。

(I'm not sure which one of them you want to do.) (我不确定你想要做其中的哪一个。)

using .apply is always a fast way to handle something like this使用 .apply 始终是处理此类事情的快速方法

#data.csv is you data
import pandas as pd
df = pd.DataFrame.read_csv('data.csv')

#you want to perform this operation on column 1 that has a label 'A'
#make a function
def col_subtract(row):
    row['A'] = row['A'] - 2.5
    return row

#apply the function to the dataframe
df = df.apply(col_subtract, axis=1)

doc 文档

note: you could also just pass it a lambda function, I just felt it was cleaner to make a formal user defined function with a name to emphasize what you're doing.注意:你也可以只传递一个 lambda 函数,我只是觉得用一个名字来强调你正在做的事情,制作一个正式的用户定义函数会更干净。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM