Date data into Year and month by using lambda function - IndexError: string index out of range

Date data into Year and month by using lambda function - IndexError: string index out of range

我正在尝试使用 str.split 和 lambda 函数从 'order_date' 创建列 'year' 和 'month'。我成功创建了 'year' 列。但是,我不断收到 'month' 列的错误消息。请帮忙!

IndexError: string index out of range

我用连字符分割字符串: 我用'0'填充了N/A: 我使用 lambda 函数创建了年份列: 我使用相同的逻辑来创建月份列,但没有成功:

orders2 = pd.DataFrame([[1,'2020-07-24 19:46:36 -0400'],[2,'2020-06-25 20:29:20 -0400'],[3,0]],columns=['order_number','order_date'])
orders2['date'] = orders2.order_date.str.split('-')
orders2.date.fillna('0',inplace=True)
orders2['year'] = orders2.apply(lambda row: row['date'][0],axis=1)
orders2['month'] = orders2.apply(lambda row: row['date'][1],axis=1)

谢谢!

选择 python 而不是 pandas 让您的生活更轻松。

import pandas as pd

orders2 = pd.DataFrame([
        [1,'2020-07-24 19:46:36 -0400'],
        [2,'2020-06-25 20:29:20 -0400'],
        [3,0]],columns=['order_number','order_date']
        )

orders2['year'] = ''
orders2['month'] = ''
for index, row in orders2.iterrows():
    try:
        year = str(row["order_date"]).split('-')[0]
        month = str(row["order_date"]).split('-')[1]
    except:
        year = '0'
        month = '0'
   
    orders2.at[index, 'year'] = year
    orders2.at[index, 'month'] = month

print(orders2)

输出:

    order_number                 order_date  year month
0             1  2020-07-24 19:46:36 -0400  2020    07
1             2  2020-06-25 20:29:20 -0400  2020    06
2             3                          0     0     0