感謝您花時間查看我的問題。Python-Pandas-Dataframe-datetime轉換不包含空值單元格
我嘗試使用下面的函數轉換熊貓數據框中的兩個日期列。我使用這個函數,因爲「Closed Date」有4221行,所以它不應該在null單元格上崩潰。
最終,更改結果爲原始行號的數據框。所以,我不想放鬆在關閉日期有空值的行。
數據幀概述:
<class 'pandas.core.frame.DataFrame'>
Int64Index: 4272 entries, 0 to 4271
Data columns (total 4 columns):
Created Date 4272 non-null object
Closed Date 4221 non-null object
Agency 4272 non-null object
Borough 4272 non-null object
dtypes: object(4)
設計功能:
col='Closed Date'
df[(df[col].notnull())] = df[(df[col].notnull())].apply(lambda x:datetime.datetime.strptime(x,'%m/%d/%Y %I:%M:%S %p'))
產生錯誤:
TypeError Traceback (most recent call last)
<ipython-input-155-49014bb3ecb3> in <module>()
9
10 col='Closed Date'
---> 11 df[(df[col].notnull())] = df[(df[col].notnull())].apply(lambda x:datetime.datetime.strptime(x,'%m/%d/%Y %I:%M:%S %p'))
12 print(type(df[(df[col].notnull())]))
/anaconda/lib/python3.6/site-packages/pandas/core/frame.py in apply(self, func, axis, broadcast, raw, reduce, args, **kwds)
4358 f, axis,
4359 reduce=reduce,
-> 4360 ignore_failures=ignore_failures)
4361 else:
4362 return self._apply_broadcast(f, axis)
/anaconda/lib/python3.6/site-packages/pandas/core/frame.py in _apply_standard(self, func, axis, ignore_failures, reduce)
4454 try:
4455 for i, v in enumerate(series_gen):
-> 4456 results[i] = func(v)
4457 keys.append(v.name)
4458 except Exception as e:
<ipython-input-155-49014bb3ecb3> in <lambda>(x)
9
10 col='Closed Date'
---> 11 df[(df[col].notnull())] = df[(df[col].notnull())].apply(lambda x:datetime.datetime.strptime(x,'%m/%d/%Y %I:%M:%S %p'))
12 print(type(df[(df[col].notnull())]))
TypeError: ('strptime() argument 1 must be str, not Series', 'occurred at index Created Date')
你爲什麼不使用'DF [COL] = pd.to_datetime(DF [COL]格式=「%M /%d /%Y%I: %M:%S%p')'? 'NaNs'將被存儲爲'NaTs' – Zero