我从 python、pandas 和 matplotlib 开始。我正在处理超过百万条目的数据。我正在尝试更改日期格式。在 CSV 文件中,日期格式为 23-JUN-11。我想在未来使用日期来绘制每个候选人的捐赠金额。如何将日期格式转换为 pandas 可读的格式?
Here is the link to cut file 149 entries
我的代码:
%matplotlib
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
第一候选人
reader_bachmann = pd.read_csv('P00000001-ALL.csv' ,converters={'cand_id': lambda x: str(x)[1:]},parse_dates=True, squeeze=True, low_memory=False, nrows=411 )
date_frame = pd.DataFrame(reader_bachmann, columns = ['contb_receipt_dt'])
数据切片
s = date_frame.iloc[:,0]
date_slice = pd.Series([s])
date_strip = date_slice.str.replace('JUN','6')
尝试转换为新的日期格式
date = pd.to_datetime(s, format='%d%b%Y')
print(date_slice)
这是错误信息
ValueError: could not convert string to float: '05-JUL-11'
最佳答案
您需要使用不同的日期格式字符串:
format='%d-%b-%y'
为什么?
错误消息给出了错误的线索:
ValueError: could not convert string to float: '05-JUL-11'
format string控制转换,目前是:
format='%d%b%Y'
需要的字段是:
%y - year without a century (range 00 to 99)
%b - abbreviated month name
%d - day of the month (01 to 31)
缺少的是分隔数据字符串中字段的 -
,以及表示两位数年份的 y
而不是当前的 Y
四位数年份。
关于python - Pandas 用字符串转换日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43525460/