python - 提取熊猫系列中的列表元素并转换为日期时间
问题描述
我现在正在处理的系列看起来像这样:
qa_answers['date_of_birth']
1 []
2 []
...
2600 [1988/11/23]
2601 [1992/7/15]
2602 [1993/11/8"]
2603 [1997/08/31]
2604 [1971/2/11]
2605 [1979/11/1"]
2606 [1993/9/19]
2607 [1985/01/12]
2608 [1977/11/3"]
2609 [1981/7/2"]
2610 [1952/4/9"]
2611 [1991/8/20]
2612 [1993/1/31]
Name: date_of_birth, dtype: object
这个问题可能包括两部分:
- 我想将系列(对象)的类型转换为日期时间。
- 但是当我尝试使用 to_datetime 时,我得到了这个错误。
qa_answers['date_of_birth'] = pd.to_datetime(qa_answers['date_of_birth'],errors='coerce')
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-147-96dff0351764> in <module>()
28 qa_answers['date_of_birth2']= qa_answers['answers'].str.findall(dob2)
29 qa_answers['date_of_birth'] = qa_answers['date_of_birth1'] + qa_answers['date_of_birth2']
---> 30 qa_answers['date_of_birth'] = pd.to_datetime(qa_answers['date_of_birth'],errors='coerce')
31
32
4 frames
/usr/local/lib/python3.6/dist-packages/pandas/core/algorithms.py in unique(values)
403
404 table = htable(len(values))
--> 405 uniques = table.unique(values)
406 uniques = _reconstruct_data(uniques, dtype, original)
407 return uniques
pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.unique()
pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable._unique()
TypeError: unhashable type: 'list'
所以我想我应该先尝试从列表中提取元素。我怎么能做这份工作?
ps 另外,您能否提供一些关于删除元素中的 '" ' 的提示?
解决方案
您必须首先将非空列表转换为其第一个元素并清理它并将空列表转换为空字符串:
df.date_of_birth.apply(lambda x: x[0].replace('"', '') if len(x) > 0 else '')
给出:
1
2
...
2600 1988/11/23
2601 1992/7/15
2602 1993/11/8
2603 1997/08/31
2604 1971/2/11
2605 1979/11/1
2606 1993/9/19
2607 1985/01/12
2608 1977/11/3
2609 1981/7/2
2610 1952/4/9
2611 1991/8/20
2612 1993/1/31
然后您可以轻松地将其转换为日期时间列:
pd.to_datetime(df.date_of_birth.apply(lambda x: x[0].replace('"', '') if len(x) > 0 else ''))
你得到:
1 NaT
2 NaT
2600 1988-11-23
2601 1992-07-15
2602 1993-11-08
2603 1997-08-31
2604 1971-02-11
2605 1979-11-01
2606 1993-09-19
2607 1985-01-12
2608 1977-11-03
2609 1981-07-02
2610 1952-04-09
2611 1991-08-20
2612 1993-01-31
Name: date_of_birth, dtype: datetime64[ns]
推荐阅读
- ruby-on-rails-5 - Rails 5 路由:为什么“redirect_to @model”与“redirect_to model_path(@model.id)”不同?
- android - Jetpack Navigation Deep Link 带有错误的 ActionBar 按钮
- azure-databricks - 在 azure databricks 中查找笔记本的沿袭
- c - 参数类型声明可以移动到函数体中吗?
- java - findView 面临的问题(Android Studio)
- c++ - 在 Mac OS X Mojave 上使用 AppleClang 编译和链接 OpenMP
- java - 砖块打破游戏:我如何打破砖块?
- javascript - 我有一种情况,如果 url 不起作用,我不想运行我的测试用例
- ios - 无法更改取消选择动画的动画持续时间
- c - 如何将混合类型数组转换为 char 数组并返回?