python - 如何将 .dbf 文件转换为 Pandas DataFrame?
问题描述
我有一个.dbf
文件,我想将其转换为 pandas DataFrame
,但DataFrame
s 无法直接转换数据。
解决方案
使用我的dbf
library,以下函数将完成这项工作:
def dbf_to_dataframe(filename):
"""
converts the dbf table at filename into a Panda's DataFrame
data types and field names are preserved
"""
import dbf
import numpy as np
import pandas as pd
from datetime import date, datetime, time
names = []
types = []
table = dbf.Table(filename)
for name in table.field_names:
ftype, size, decimals, _ = table.field_info(name)
ftype = chr(ftype)
if ftype in 'GP':
continue
if ftype == 'N' and decimals:
ftype = 'F'
dtype = {
'B': 'float64',
'C': 'string',
'D': 'datetime64[ns]',
'F': 'float64',
'I': 'int64',
'L': 'boolean',
'M': 'string',
'N': 'int64',
'T': 'datetime64[ns]',
'Y': 'float64',
}[ftype]
names.append(name)
types.append(dtype)
with table:
series = [[] for _ in names]
for rec in table:
for i, value in enumerate(rec):
if isinstance(value, date):
value = datetime.combine(value, time())
elif value is None:
value = np.nan
series[i].append(value)
data_recs = dict(
(n, pd.Series(s, dtype=t))
for n, s, t in zip(names, series, types)
)
return pd.DataFrame(data_recs)
推荐阅读
- reactjs - 如何在屏幕上显示从输入表单计算的值
- entity-framework - EF 模型未从数据库正确更新
- azure - Azure 数据工厂复制数据管道只是停留在进行中状态;但甚至没有加载任何数据
- amazon-web-services - 运行 cron 作业时“端点 URL 连接超时”
- python - 我必须压缩许多相似的文件,我可以利用它们相似的事实吗?
- reactjs - 视频结束时的视频反应回调?
- java - 创建洗牌程序Java
- python - 如何使用python调用和循环分页API
- reactjs - 如何在 ReactJS 和 Spring Security 中实现 OAuth?
- javascript - 数组移位和求和