python - 当我最初不知道数据类型时,如何快速更改 100 多个数据帧的格式?
问题描述
在使用 Pandas 读取数据帧后,我试图格式化很多(>100)数据帧。这些不是大型数据集(最大文件大小约为 50 MB),但具有不同数量的列(10-100)和不同的列名(有些是相同的),可以有整数、浮点数、日期时间或字符串值. 最终目标是将它们合并到一个数据框中,但在此之前,我需要正确设置每一列的格式。我希望加快这个过程。
编辑:列的每个数据类型都作为“对象”返回。我试过 df.infer_objects() 但这只是返回了相同的数据类型。
我目前的格式化功能是
def format_df(df):
'''
Formats the dataframe in the way I want.
Parameters
-----------
df: a pandas.DataFrame - dataframe with unformatted data types
Returns
-----------
df1: a pandas.DataFrame - dataframe with correct data types
'''
start = time.time()
# Copy dataframe to make changes
df1 = df.copy()
# Format the correct data type for each column in the dataframe
for col in df.columns:
try:
# Tries to convert column to datetime format
df1[col] = df[col].map(pd.to_datetime)
# If entire column is null, then convert to NaN instead of NaT
if len(df1[df1[col].isnull() == True]) == len(df1[col]):
df1[col] = df1[col].astype(object).where(df1[col].notnull(),
np.nan)
df1[col] = df1[col].astype(float)
except:
# If it can't convert to datetime, try converting to a numeric
# format (int or float)
try:
df1[col] = df[col].map(pd.to_numeric)
except:
# If data is not datetime or numeric (i.e. string of
# characters), leave as is
df1[col] = df[col]
end = time.time()
print('Time to format dataframe: ', (end-start)/60)
return df1
在数据集上运行该函数需要 30 秒到 2 分钟,但由于我有超过 100 个数据帧,整个过程大约需要 30 分钟。我怎样才能让它更快?
我还在研究一种在读取文件之前获取列数据类型的方法,但我不确定这会更快。
解决方案
推荐阅读
- angular - 如何在没有附加组件的情况下在多个地方重用 HTML
- javascript - 解析 RSS 提要信息并显示在 HTML 页面上
- cassandra - Cassandra插入值消失
- c++ - 如果任何列中都不需要图像/图标,MFC CListCtrl 是否合适?
- python-3.x - Python 代码在行中使用 3 次时交换 csv 列(连续 3 天)
- c# - 如何修复我的 c# 二进制搜索算法?
- visual-studio-2015 - Visual Studio 2017/IIS Express:无法连接到已配置的开发 Web 服务器
- api - 如何验证 Analytics 360 是否与 BigQuery 成功关联?
- regex - 使用 4 个或更少 OR 语句的数字 -25 到 1045 的正则表达式
- regex - 使用 RegEx 匹配带有和不带有转义字符的字符串