nnnnmmm
nnnnmmm

Reputation: 243

Extract day of the week from column in dataframe and put in another column

# Give day of the week
def DOW(df):
    DOW = pd.Series(datetime.datetime.strptime(df['indx'],'%Y%m%d').strftime('%A'))
    df = df.join(DOW)
    return df

I am calling this function from another script as where d is my dataframe which I pass to function DOW

 d = TA.DOW(d)

It throws the error . what can be solution for same

DOW=pd.Series(datetime.datetime.strptime(df['indx'],'%Y%m%d').strftime('%A'))
TypeError: must be string, not Series

Upvotes: 1

Views: 62

Answers (1)

jezrael
jezrael

Reputation: 862661

I think you can first convert column indx to_datetime and then use dt.strftime as mentioned EdChum:

print df
       indx  Value
0  20020101   3.00
1  20020102   3.50
2  20020103   3.30
3  20100101   4.96
4  20100102   4.98

df['new'] = pd.to_datetime(df['indx'], format='%Y%m%d').dt.strftime('%A') 
print df
       indx  Value        new
0  20020101   3.00    Tuesday
1  20020102   3.50  Wednesday
2  20020103   3.30   Thursday
3  20100101   4.96     Friday
4  20100102   4.98   Saturday

Upvotes: 1

Related Questions