dokondr
dokondr

Reputation: 3539

How to create multiple additional columns from dataframe and add to the same dataframe

Trying to parse 'date' column into 'month', 'day', 'hour' and 'minute' and then add them as separate columns to the same dataframe:

import pandas as pd
d = {'date':[pd.Timestamp('2019-03-01 00:05:01'),
             pd.Timestamp('2019-04-02 07:11:00'),
             pd.Timestamp('2019-05-03 10:25:00')], 
     'foo': ['abc','def','jhk']
}
df1 = pd.DataFrame(d)

    date                foo
0   2019-03-01 00:05:01 abc
1   2019-04-02 07:11:00 def
2   2019-05-03 10:25:00 jhk

After extracting 'times':

times = df1['date'].apply(lambda date: (date.month, date.day, date.hour, date.minute))

I try to add them to the dataframe as separate columns:

df1['month'], df1['day'], df1['hour'], df1['minute'] = times

Which results in error:

 ValueError                                Traceback (most recent call last)
 <ipython-input-21-171174d71b13> in <module>
  ----> 1 df1['month'], df1['day'], df1['hour'], df1['minute'] = times

 ValueError: not enough values to unpack (expected 4, got 3)

How to add 'times' as separate columns?

Upvotes: 1

Views: 60

Answers (2)

Fourier
Fourier

Reputation: 2983

Alternatively, use pd.assign:

df1.assign(month=df1["date"].dt.month, day=df1["date"].dt.day, hour=df1["date"].dt.hour, minutes=df1["date"].dt.minute)

Output:

                  date  foo  month  day  hour   minutes
0   2019-03-01 00:05:01 abc     3     1    0          5
1   2019-04-02 07:11:00 def     4     2    7         11
2   2019-05-03 10:25:00 jhk     5     3   10         25

Upvotes: 1

yatu
yatu

Reputation: 88226

Looks like you want

df1['month'], df1['day'], df1['hour'], df1['minute'] =  (df1.date.dt.month, df1.date.dt.day, 
                                                        df1.date.dt.hour, df1.date.dt.minute)

print(df1)

date  foo  month  day  hour  minute
0 2019-03-01 00:05:01  abc      3    1     0       5
1 2019-04-02 07:11:00  def      4    2     7      11
2 2019-05-03 10:25:00  jhk      5    3    10      25
​

Upvotes: 1

Related Questions