Reputation: 219
I have a question regarding adding a column table with different type of values: e.g. the length of the table is 10 rows. The first be given 1 of January, second row 1 of February, 3 row -1 of march etc.
Is there a function that enables this instead of writing everything "by hand".
Thanks in advance.
Upvotes: 0
Views: 323
Reputation: 863166
I think you need helper DataFrame
and then join
column to original.
Notice:
index
of df
is default, it means unique, monotonic (0,1,2...
)
#create date range longer as max length of original df
df1 = pd.DataFrame({'rng': pd.date_range('2016-01-01', periods=1000)})
#convert to string and remove trailing 0
df1['new'] = df1['rng'].dt.strftime('%d of %B').str.lstrip('0')
#extract year, month, days
df1 = df1.assign(year=df1['rng'].dt.year,month=df1['rng'].dt.month, day=df1['rng'].dt.day)
#sorting and create default index (0,1,2)
df1 = df1.sort_values(['year','day','month']).reset_index(drop=True)
print (df1.head())
rng new day month year
0 2016-01-01 1 of January 1 1 2016
1 2016-02-01 1 of February 1 2 2016
2 2016-03-01 1 of March 1 3 2016
3 2016-04-01 1 of April 1 4 2016
4 2016-05-01 1 of May 1 5 2016
df = pd.DataFrame({'A':list('abcdef'),
'B':[4,5,4,5,5,4]})
df = df.join(df1['new'])
print(df)
A B new
0 a 4 1 of January
1 b 5 1 of February
2 c 4 1 of March
3 d 5 1 of April
4 e 5 1 of May
5 f 4 1 of June
Upvotes: 2