gpt4 book ai didi

python - 更改数据框中一组条目的数据类型

转载 作者:太空宇宙 更新时间:2023-11-03 14:41:08 25 4
gpt4 key购买 nike

我已将包含 15 列和 100,000 多行的 csv 文件导入到数据框中。其中一栏是“出生”,表示出生年份。在“birth”列中,实际上有 3 种不同的字符串类型格式,其中以“02-Aug-34”的格式列出日期,以“29DEC1899”的格式列出日期,最后一个为空白字符串格式“”。

我编写了一个脚本,可以对“出生”字符串的类型进行排序,然后将非空白字符串转换为给定日期的日期时间格式。我使用一个循环,通过行号迭代适当的列表,以将数据框“出生”条目从字符串替换为日期时间,基本上覆盖以前的值。

浏览 100,000 多个条目大约需要 130 秒。考虑到输入值的 3 种不同可能情况,是否有更有效的方法来转换数据类型?这个完成时间(130 秒左右)合理吗?

我对使用 pandas 很陌生。

最佳答案

您可以使用to_datetime每种格式两次,然后 combine_first :

此外,02-Aug-15 有时也不能是 02-Aug-181502-Aug-191502- 2015 年 8 月,因为无法区分它。

df = pd.DataFrame({'date':['02-Aug-34','29DEC1899','02-Aug-15','']})

#format 29DEC1899
d1 = pd.to_datetime(df['date'], format='%d%b%Y', errors='coerce')

#replace last - to 19
dates = df['date'].str.replace(r'(.*)-', r'\1-19')
#alternative1
#dates = df['date'].str[::-1].str.replace('-', '91-', n=1).str[::-1]
#alternative2
#dates = df['date'].str.rsplit('-', n=1).str.join('-19')

#format 02-Aug-34
d2 = pd.to_datetime(dates, format='%d-%b-%Y', errors='coerce')

#combine formats
d = d1.combine_first(d2)
print (d)
0 1934-08-02
1 1899-12-29
2 1915-08-02
3 NaT
Name: date, dtype: datetime64[ns]

关于python - 更改数据框中一组条目的数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46537283/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com