1

所以我有一个 Pandas DF,其中有许多需要日期时间的日期字段,所以我有以下工作,但知道它是糟糕的 Python,至少每个字段循环整个 DF 一次,并且 df 是 410,000 行。

table.index=pd.to_datetime(table.index) #not sure why it does not come in as datetime?
table['STATUS_DATE']=pd.to_datetime(table['STATUS_DATE'])
table['DATE_MODIFIED']=pd.to_datetime(table['DATE_MODIFIED'])
table['SOLD_DATE']=pd.to_datetime(table['SOLD_DATE'])
table['WITHDRAWN_DATE']=pd.to_datetime(table['WITHDRAWN_DATE'])
table['END_DATE']=table[['DATE_MODIFIED', 'STATUS_DATE','SOLD_DATE','WITHDRAWN_DATE']].min(axis=1)
table['SUBDIVISION'].replace(df3['NSUBDIVISION'],inplace=True)
table['CALC_DOM']=table.index # there should be a single line version???
table['CALC_DOM']=table['END_DATE']-table['CALC_DOM']

我想循环一次df并转换所有字段?欢迎提出建议 我刚刚开始能够写一些这样的东西,但想学会正确地做,而不是我上面那些丑陋的东西。

4

1 回答 1

2

看到我上面的评论,但你可以这样做:

In [5]: df = DataFrame(randn(10,1))

In [6]: df['col1'] = '20130101'

In [7]: df['col2'] = '20130102 9:01'

In [8]: df
Out[8]: 
          0      col1           col2
0 -1.111980  20130101  20130102 9:01
1  1.417732  20130101  20130102 9:01
2 -0.111606  20130101  20130102 9:01
3 -0.999599  20130101  20130102 9:01
4 -0.229082  20130101  20130102 9:01
5  0.535978  20130101  20130102 9:01
6 -1.913625  20130101  20130102 9:01
7  1.000879  20130101  20130102 9:01
8  0.358047  20130101  20130102 9:01
9  0.764761  20130101  20130102 9:01

In [9]: col_list = ['col1','col2']

In [10]: df[col_list] = df[col_list].apply(lambda x: pd.to_datetime(x))

In [11]: df
Out[11]: 
          0                col1                col2
0 -1.111980 2013-01-01 00:00:00 2013-01-02 09:01:00
1  1.417732 2013-01-01 00:00:00 2013-01-02 09:01:00
2 -0.111606 2013-01-01 00:00:00 2013-01-02 09:01:00
3 -0.999599 2013-01-01 00:00:00 2013-01-02 09:01:00
4 -0.229082 2013-01-01 00:00:00 2013-01-02 09:01:00
5  0.535978 2013-01-01 00:00:00 2013-01-02 09:01:00
6 -1.913625 2013-01-01 00:00:00 2013-01-02 09:01:00
7  1.000879 2013-01-01 00:00:00 2013-01-02 09:01:00
8  0.358047 2013-01-01 00:00:00 2013-01-02 09:01:00
9  0.764761 2013-01-01 00:00:00 2013-01-02 09:01:00
于 2013-08-16T20:04:02.727 回答