Jingtao Yun Jingtao Yun - 1 year ago 63
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:

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

Answer Source

You can use assign:


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

           A  B
0 2015-01-01  1
1 2014-07-02  2
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download