python3 readexcel pandas问题,使用python中的pandas中的read_excel函数将日期保留为字符串...
Python 2.7.10
Tried pandas 0.17.1 -- function read_excel
Tried pyexcel 0.1.7 + pyexcel-xlsx 0.0.7 -- function get_records()
在Python中使用pandas時,是否可以讀取excel文件(格式:xls | xlsx)并將包含 date 或 date + time 值的列保留為 strings 而不是 auto-converting 為 datetime.datetime 或 timestamp 類型?
如果使用pandas無法做到這一點,有人會建議使用備用方法/庫來讀取xls | xlsx文件并將日期列值保留為字符串嗎?
對于 pandas 解決方案,嘗試 df.info() 和結果日期列類型如下所示:
>>> df.info()
Int64Index: 117 entries, 0 to 116
Columns: 176 entries, Mine to Index
dtypes: datetime64[ns](2), float64(145), int64(26), object(3)
memory usage: 161.8+ KB
>>> type(df['Start Date'][0])
Out[6]: pandas.tslib.Timestamp
>>> type(df['End Date'][0])
Out[7]: pandas.tslib.Timestamp
Attempt/Approach 1:
def read_as_dataframe(filename, ext):
import pandas as pd
if ext in ('xls', 'xlsx'):
# problem: date columns auto converted to datetime.datetime or timestamp!
df = pd.read_excel(filename) # unwanted - date columns converted!
return df, name, ext
Attempt/Approach 2:
import pandas as pd
# import datetime as datetime
# parse_date = lambda x: datetime.strptime(x, '%Y%m%d %H')
parse_date = lambda x: x
elif ext in ('xls', 'xlsx', ):
df = pd.read_excel(filename, parse_dates=False)
date_cols = [df.columns.get_loc(c) for c in df.columns if c in ('Start Date', 'End Date')]
# problem: date columns auto converted to datetime.datetime or timestamp!
df = pd.read_excel(filename, parse_dates=date_cols, date_parser=parse_date)
并且還嘗試了pyexcel庫,但它執行相同的自動魔術轉換行為:
Attempt/Approach 3:
import pyexcel as pe
import pyexcel.ext.xls
import pyexcel.ext.xlsx
t0 = time.time()
if ext == 'xlsx':
records = pe.get_records(file_name=filename)
for record in records:
print("start date = %s (type=%s), end date = %s (type=%s)" %
(record['Start Date'],
str(type(record['Start Date'])),
record['End Date'],
str(type(record['End Date'])))
)
總結
以上是生活随笔為你收集整理的python3 readexcel pandas问题,使用python中的pandas中的read_excel函数将日期保留为字符串...的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ios音乐播放器demo
- 下一篇: 硬件:电脑基础进阶必学知识,详解电脑主板