我正在尝试获取年份的后两位数字(即“ 2000”中的“ 00”)。这是我所拥有的:
设置简单的df,在“年份”列中输入
import pandas as pd
df = pd.DataFrame.from_dict({'20000701':[1,1,1], '20010701':[2,2,2]},orient='index',columns=['c0','c1','c2'])
df['Datetime']=pd.to_datetime(df.index)
df['year']=df['Datetime'].dt.strftime('%Y')
print(df)
c0 c1 c2 Datetime year
20000701 1 1 1 2000-07-01 2000
20010701 2 2 2 2001-07-01 2001
然后我尝试将year转换为字符串并获取最后2个:
df['year2']=str(df['year'])[-2:]
df['year2']
但这给了我“ ct”,我不明白:
c0 c1 c2 Datetime year year2
20000701 1 1 1 2000-07-01 2000 ct
20010701 2 2 2 2001-07-01 2001 ct
答案 0 :(得分:1)
尝试一下:
update big_table b
set b.something = (select c.something_else from mission_critical c where b.refID = c.id)
或者:
df['year2']=df.year.str[2:]
print(df)
答案 1 :(得分:0)
看来,最简单的答案是在strftime中使用小写的y:
## Thank you slide {.thank-you-slide}
那么就不需要.str [2:]
尽管如此,基于anky_91的回答,我还是感到困惑:
df['year']=df['Datetime'].dt.strftime('%y')
但这不是:
df['year']=df.year.str[2:]
显然您需要:
df['month']=df['Datetime'].dt.strftime('%m')
df['month']=df.month.str
或者只是:
df['month']=df.month.str[:]