0

I have a problem after changing reading the excel file from pd.read_excel() to pd.read_csv() for below code.

When using pd.read_excel(), no below error pops up,but for performance issue, I still need to use pd.read_csv().

I have tried to changemany thanks in advance:

  t_date=pd.read_csv('D:/data.csv',encoding='utf-8',parse_dates=True)
  t_date['Item Creation Date'] = t_date['Item Creation Date'].fillna('')
  t_date['Item Creation Date']=pd.to_datetime(t_date['Item Creation Date'])
  t_date['Order_WK']=t_date[['Item Creation Date']].apply(lambda x:(x['Item Creation Date']+relativedelta(weekday=SU)).strftime("%Y%m%d"),axis=1)

TypeError: ('can only concatenate str (not "relativedelta") to str', 'occurred at index 0')
Héléna
  • 1,075
  • 3
  • 14
  • 39
  • 1
    Your `"Item Creation Date"` column is a `string`, not a `datetime` object. You need to pass `parse_dates=["Item Creation Date"]` to `pd.read_csv`. – PMende Feb 12 '20 at 02:08
  • 1
    you need to convert `relativedelta(weekday=SU)` to a string. Can you let us know what is the value of variable `relativedelta(weekday=SU)` as of now? – moys Feb 12 '20 at 02:08
  • 1
    try replacing `x['Item Creation Date']+relativedelta(weekday=SU)` with `(x['Item Creation Date']+relativedelta(weekday=SU)).strftime("%Y%m%d")`. You can change `%Y%m%d` to your desired format ( `%m%d%Y` or `%m%d%Y%H:%M:%S`....and so on) – moys Feb 12 '20 at 02:14
  • @Héléna so, you may have `NaT` in the column `x['Item Creation Date']`. try fixing that first by either removing it or coercing it to get a date vaue instead of `NaT` – moys Feb 12 '20 at 02:21
  • Please provide your input dataframe or at-least `t_date['Item Creation Date']` – moys Feb 12 '20 at 02:22
  • @Héléna `.fillna('')` will also not work because `x['Item Creation Date']+relativedelta(weekday=SU))` has to be a date for `.strftime("%Y%m%d")` to work on it. – moys Feb 12 '20 at 02:32
  • @moys hi since I have "pd.to_datetime(t_date['Item Creation Date'])" , it is already been converted to a date and should work for .strftime("%Y%m%d"), is my understanding correct? – Héléna Feb 12 '20 at 02:36
  • @PMende hi parse_dates is added in pd.read_csv(...parse_dates=True), is that what you suggest? tks~ – Héléna Feb 12 '20 at 02:38
  • @Héléna please double check if all rows of column `t_date['Item Creation Date']` are dates. Even if one of them is also not a date (`NaT` or something like that, even blank), it will not work. If you can provide your input dataframe or at-least `t_date['Item Creation Date']` , we can help you better. – moys Feb 12 '20 at 02:39
  • @moys I see the reason now, many thanks – Héléna Feb 12 '20 at 04:15

0 Answers0