0

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.

3
  • Well i just want to add that type of column, so i guess it would be a string. Commented Aug 28, 2017 at 11:38
  • Can you add an example of your current data set, and what you want the end result to look like? Here's some guidelines Commented Aug 28, 2017 at 11:45
  • I guess i was unclear with my question. What i mean is let say one column of 10 rows contains values, i want to add additional column with units, however the differ from each other, so first 3 rows has the unit of "kWh" and the rest of the Rows have "MWh" Commented Aug 29, 2017 at 9:19

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.