Jingtao Yun Jingtao Yun - 2 months ago 8
Python Question

What pandas function does change the column type in an "inline" manner?

I know that the following commands could help change the column type:

df['date'] = str(df['date'])

df['A'] = pd.to_datetime(df['A'])

df['A'] = df.A.astype(np.datetime64)


But do you know a better way to change the column type in an inline manner to make it in one line following with other aggregating commands such as groupby, dropna, etc. For example:

df\
#.function to cast df.A to np.datetime64 \
.groupby('C') \
.apply(lambda x: x.set_index('A').resample('1M').sum())

Answer

You can use assign:

df.assign(A=pd.to_datetime(df['A']))

df = pd.DataFrame({'A': ['20150101', '20140702'], 'B': [1, 2]})
df
Out: 
          A  B
0  20150101  1
1  20140702  2

df.assign(A=pd.to_datetime(df['A']))
Out: 
           A  B
0 2015-01-01  1
1 2014-07-02  2