有没有办法在Python中从日期中减去另一列中指定的年份?

huangapple go评论121阅读模式
英文:

Is there a way to subtract from the date a year specified in another column in python?

问题

今天我遇到了一些挑战。

这是一个示例数据集:

example = {
"a": ['1/1/1954 14:14','2/14/2001 2:00' , '2/15/2002 12:00'],
"b": [1936,1996,1960],
}

# 加载到数据框中:
example = pd.DataFrame(example)

print(example) 

我尝试的操作是:

example['c'] = example['a'] - example['b']

然而,我遇到了问题:

不支持的操作数类型:'str' 和 'int'

我尝试将字符串转换为整数,但没有成功。

请问您能否推荐一些包或方法来处理这个减法操作?我听说过datetime,但不确定如何相应地设置来自列"a"的日期。

非常感谢!

英文:

Today I have confronted some challenges.

This is an example dataset:

example = {
"a": ['1/1/1954 14:14','2/14/2001 2:00' , '2/15/2002 12:00'],
"b": [1936,1996,1960],
}

#load into df:
example = pd.DataFrame(example)

print(example) 

What I was trying to do is:

example['c'] = example['a'] - example['b']

However, I got the issue:

unsupported operand type(s) for -: 'str' and 'int'

I tried to convert the string to the integer, but it did not work.

Could you please recommend me some package or a method to deal with this subtraction? I have heard about datetime, but I am not sure how to set the dates from column "a" accordingly.

Thank you in advance!

答案1

得分: 2

将值转换为日期时间并提取年份:

y = pd.to_datetime(example['a']).dt.year
example['c'] = y - example['b']

或者提取斜杠和空格之间长度为4的整数:

y = example['a'].str.extract(r'/(\d{4})\s+', expand=False).astype(int)
example['c'] = y - example['b']
英文:

Convert values to datetimes and extract years:

y = pd.to_datetime(example['a']).dt.year
example['c'] = y - example['b']

Or extract integers with length 4 between / and space:

y = example['a'].str.extract(r'/(\d{4})\s+', expand=False).astype(int)
example['c'] = y - example['b']

huangapple
  • 本文由 发表于 2023年3月7日 17:02:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/75659864.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定