一列有日期,而另一列有一个包含日期的字符串,所以我首先需要从该字符串中提取日期部分。
import pandas as pd
import datetime
from dateutil.relativedelta import relativedelta
# the dataframe - id column always starts with year, month and day
df = pd.DataFrame({'id': ['19520630F8', '19680321A5', '19711113E2'],
'dte': ['2010-06-02', '2007-08-12', '2013-01-23']})
# create a date string from df['id'] to the format yyyy-mm-dd
dob = (df['id'].str[:4] + '-' +
df['id'].str[4:6] + '-' +
df['id'].str[6:8])
# calculate age (years only) at df['dte']
df['age'] = relativedelta(date, dob).years
Run Code Online (Sandbox Code Playgroud)
我收到错误消息:
ValueError:系列的真值不明确。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。
我不明白我的数据的歧义,以及在哪里应用那些空/布尔/项目......df['dta']
对象数据类型而不是日期时间的列if,但将dob的创建包装在pd.to_datetime
无济于事。
编辑预期的输出应该是
dte id …
Run Code Online (Sandbox Code Playgroud) 在数据框中
\n\ndf = pd.DataFrame({'c1': ['c10:b', 'c11', 'c12:k'], 'c2': ['c20', 'c21', 'c22']})\n\n c1 c2\n0 c10:b c20\n1 c11 c21\n2 c12:k c22\n
Run Code Online (Sandbox Code Playgroud)\n\n我想修改 c1 列的字符串值,以便删除冒号之后(包括)的所有内容,因此最终结果如下:
\n\n c1 c2\n0 c10 c20\n1 c11 c21\n2 c12 c22\n
Run Code Online (Sandbox Code Playgroud)\n\n我试过切片
\n\ndf[\xe2\x80\x99c1\xe2\x80\x99].str[:df[\xe2\x80\x99c1\xe2\x80\x99].str.find(\xe2\x80\x99:\xe2\x80\x99)]\n
Run Code Online (Sandbox Code Playgroud)\n\n但它不起作用。我该如何实现这个目标?
\n