从数据框中的列中提取星期几并放入另一列
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
我从另一个脚本调用这个函数,因为 d 是我传递给函数 DOW 的数据帧
d = TA.DOW(d)
它抛出错误。什么可以解决同样的问题
DOW=pd.Series(datetime.datetime.strptime(df['indx'],'%Y%m%d').strftime('%A'))
TypeError: must be string, not Series
我想你可以先转换列 indx
to_datetime
and then use dt.strftime
as mentioned :
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
# 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
我从另一个脚本调用这个函数,因为 d 是我传递给函数 DOW 的数据帧
d = TA.DOW(d)
它抛出错误。什么可以解决同样的问题
DOW=pd.Series(datetime.datetime.strptime(df['indx'],'%Y%m%d').strftime('%A'))
TypeError: must be string, not Series
我想你可以先转换列 indx
to_datetime
and then use dt.strftime
as mentioned
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