ineedanswerz
ineedanswerz

Reputation: 13

How to extract a item from list of items in a python dataframe column?

I have a Dataframe like this :

  Date         sdate  
0 2012-3-12   [2012, 03, 12]
1 2012-3-25   [2012, 03, 25]
2 2012-4-20   [2012, 04, 20]
3 2012-4-12   [2012, 04, 12]
4 2012-4-26   [2012, 04, 26]

I need to extract the year,month and day to separate columns like this

           Date            sdate     year   month  day 
    0 2012-3-12   [2012, 03, 12]    2012      03   12
    1 2012-3-25   [2012, 03, 25]    2012      03   25 
    2 2012-4-20   [2013, 04, 20]    2013      04   20
    3 2012-4-12   [2015, 06, 12]    2015      06   12
    4 2012-4-26   [2011, 08, 26]    2011      08   26

Can I achieve this using for loop?

Upvotes: 1

Views: 842

Answers (1)

Zero
Zero

Reputation: 76947

Use apply with pd.Series and rename the columns

In [784]: df.sdate.apply(pd.Series).rename(columns={0:'year',1:'month',2:'day'})
Out[784]:
   year  month  day
0  2012      3   12
1  2012      3   25
2  2012      4   20
3  2012      4   12
4  2012      4   26

join to original df

In [785]: df.join(df.sdate.apply(pd.Series).rename(columns={0:'year',1:'month',2:'day'}))
Out[785]:
        Date          sdate  year  month  day
0  2012-3-12  [2012, 3, 12]  2012      3   12
1  2012-3-25  [2012, 3, 25]  2012      3   25
2  2012-4-20  [2012, 4, 20]  2012      4   20
3  2012-4-12  [2012, 4, 12]  2012      4   12
4  2012-4-26  [2012, 4, 26]  2012      4   26

Or, provide column names as index

In [786]: df.sdate.apply(lambda x: pd.Series(x,  index=['year', 'month', 'day']))
Out[786]:
   year  month  day
0  2012      3   12
1  2012      3   25
2  2012      4   20
3  2012      4   12
4  2012      4   26

Upvotes: 2

Related Questions