Home > Net >  Assigning to pandas dataframe column using formatted string leads to error
Assigning to pandas dataframe column using formatted string leads to error

Time:11-29

The following code for getting the week number and year works:

df['weekNo'] = df['date'].dt.isocalendar().week
df['year'] = df['date'].dt.year

but,

df['weekYear'] = "%d/%d" % (df['date'].dt.isocalendar().week, df['date'].dt.year)

Gives the error: %d format: a number is required, not Series

I am accessing the week and year in a way that accesses the series of values, as shown by the first code snippet. Why doesn't that work when I want a formatted string? How do I re-write the code in snippet 2, to make it work? I don't want to make intermediate columns.

Many thanks

CodePudding user response:

Most of time we can do dt.strftime, which accepts format codes.

df['new'] = pd.to_datetime(df['date']).dt.strftime('%V/%Y')

CodePudding user response:

If you want to use the formatting, can use map to get that map or apply the formatting to every road, the .dt is not needed since you will be working with date itself, not Series of dates. Also isocalendar() returns a tuple where second element is the week number:

df["date"] = pd.to_datetime(df["date"]) 
df['weekYear'] =  df['date'].map(lambda x: "%d/%d" % (x.isocalendar()[1], x.year))

CodePudding user response:

You can just use:

df['weekYear'] = df['date'].dt.isocalendar().week.astype(str)   '/'    df['date'].dt.year.astype(str)

Or using pandas.Series.str.cat

df['weekYear'] = df['date'].dt.isocalendar().week.astype(str).str.cat(df['date'].dt.year.astype(str), sep='/')

Or using list comprehension

df['weekYear'] = [f"{week}/{year}" for week, year in zip(df['date'].dt.isocalendar().week, df['date'].dt.year)]
  • Related