Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/72.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python中添加年份到日期(d-m-y)列_Python_Pandas - Fatal编程技术网

在Python中添加年份到日期(d-m-y)列

在Python中添加年份到日期(d-m-y)列,python,pandas,Python,Pandas,我有一个Col1数据表,其日期为格式(2019-08-19),另一个Col2数据表的年份为格式(1年为1年,2年为2年…),目标是将Col1添加到Col2的新col中,结果为2020-08-19 我做了if函数,但很长时间我想要简单易行的方法。一个简单易用的方法是: 以第1列为例,按催眠将其拆分 a = cell.split('-') 列表中的第一个条目将是年度字符串。将其转换为整数,然后将其添加到第二列(也转换为整数)的值中 a[0] = str(int(a[0]) + int(col2ce

我有一个Col1数据表,其日期为格式(2019-08-19),另一个Col2数据表的年份为格式(1年为1年,2年为2年…),目标是将Col1添加到Col2的新col中,结果为2020-08-19


我做了if函数,但很长时间我想要简单易行的方法。

一个简单易用的方法是:

以第1列为例,按催眠将其拆分

a = cell.split('-')
列表中的第一个条目将是年度字符串。将其转换为整数,然后将其添加到第二列(也转换为整数)的值中

a[0] = str(int(a[0]) + int(col2cell))
然后将列表中的值与中间的hypen重新组合

newcell = a[0] + '-' + a[1] + '-' + a[2]

对每行执行此操作。

一个简单的方法是:

以第1列为例,按催眠将其拆分

a = cell.split('-')
列表中的第一个条目将是年度字符串。将其转换为整数,然后将其添加到第二列(也转换为整数)的值中

a[0] = str(int(a[0]) + int(col2cell))
然后将列表中的值与中间的hypen重新组合

newcell = a[0] + '-' + a[1] + '-' + a[2]
对每行执行此操作。

您需要与一起使用

最简单的例子:

df = pd.DataFrame({
    'col1': ['2019-08-19', '2019-04-25'],
    'col2': [1,2]
})
df['col1'] = pd.to_datetime(df['col1'])
df['col1'] = df.apply(lambda x: x['col1'] + pd.DateOffset(years=x['col2']), axis=1)
输出:

0   2020-08-19
1   2021-04-25
dtype: datetime64[ns]
你需要使用

最简单的例子:

df = pd.DataFrame({
    'col1': ['2019-08-19', '2019-04-25'],
    'col2': [1,2]
})
df['col1'] = pd.to_datetime(df['col1'])
df['col1'] = df.apply(lambda x: x['col1'] + pd.DateOffset(years=x['col2']), axis=1)
输出:

0   2020-08-19
1   2021-04-25
dtype: datetime64[ns]

谢谢,你能解释一下为什么最后是1吗?@Gogo78,我在答案中添加了文档的链接。请编辑。为了回答特定的问题,
axis=1
用于
为每一行应用一个特定的函数。@Gogo78当您看到axis=1时,它意味着在行上应用它(相反,axis=0意味着在列上应用它)。我不知道为什么我在尝试此类型时仍会出错错误:(“不支持的操作数类型)对于+:'Date'和'relativedelta','发生在索引0')其他=其他+self。_偏移量类型错误:(+:'Date'和'relativedelta'不支持的操作数类型,发生在索引0')谢谢,你能解释为什么最后是1吗?@GOGOO78,我在答案中添加了文档的链接。请编辑。为了回答特定的问题,
axis=1
用于
为每一行应用一个特定的函数。@Gogo78当您看到axis=1时,它意味着在行上应用它(相反,axis=0意味着在列上应用它)。我不知道为什么我在尝试此类型时仍会出错错误:(“不支持的操作数类型)对于+:'Date'和'relativedelta','发生在索引0'其他=其他+self.\u偏移量类型错误:(+:'Date'和'relativedelta'不支持的操作数类型,'发生在索引0'上)