Python正在推断列数据类型
我正在将JSON文件读入数据帧。数据帧可能有一些字符串(对象)类型的列、一些数字(int64和/或float64)和一些日期时间类型的列。读入数据时,数据类型通常不正确(即datetime、int和float通常存储为“object”类型)。我想报告一下这种可能性。(即列在数据帧中作为“对象”(字符串),但实际上是“日期时间”) 我遇到的问题是,当我使用pd.to\u numeric和pd.to\u datetime时,它们都会计算并尝试转换列,很多时候,结果取决于我最后调用的两个列中的哪一个。。。(我打算使用convert_objects(),它可以正常工作,但会贬值,所以需要一个更好的选项) 我用来评估dataframe列的代码是(我意识到下面的许多代码是多余的,但为了可读性,我以这种方式编写了它): 试试看Python正在推断列数据类型,python,pandas,profiling,Python,Pandas,Profiling,我正在将JSON文件读入数据帧。数据帧可能有一些字符串(对象)类型的列、一些数字(int64和/或float64)和一些日期时间类型的列。读入数据时,数据类型通常不正确(即datetime、int和float通常存储为“object”类型)。我想报告一下这种可能性。(即列在数据帧中作为“对象”(字符串),但实际上是“日期时间”) 我遇到的问题是,当我使用pd.to\u numeric和pd.to\u datetime时,它们都会计算并尝试转换列,很多时候,结果取决于我最后调用的两个列中的哪一个。
df['field_name'] = df['field_name'].astype(np.float64)
(假设
将numpy导入为np
)或者:Pandas允许您在创建数据帧时明确定义数据类型。传入一个字典,其中列名作为键,所需的数据类型作为值
对于标准构造函数
或者,可以在导入到数据框后强制转换列的类型
例如:
df['field\u name']=df['field\u name'].astype(np.date\u time)
让它推断数据类型的一个解决方案是让它使用StringIO
将数据写入CSV,然后将其读回。我遇到了同样的问题,即必须为事先不知道类型的传入数据找出列类型(从我的案例中读取的数据库中)。我在这里找不到好的答案,或者通过查看Pandas源代码。我使用以下函数解决了这个问题:
def _get_col_dtype(col):
"""
Infer datatype of a pandas column, process only if the column dtype is object.
input: col: a pandas Series representing a df column.
"""
if col.dtype == "object":
# try numeric
try:
col_new = pd.to_datetime(col.dropna().unique())
return col_new.dtype
except:
try:
col_new = pd.to_numeric(col.dropna().unique())
return col_new.dtype
except:
try:
col_new = pd.to_timedelta(col.dropna().unique())
return col_new.dtype
except:
return "object"
else:
return col.dtype
在Pandas API的深处,实际上有一个函数做得相当不错
import pandas as pd
infer_type = lambda x: pd.api.types.infer_dtype(x, skipna=True)
df.apply(infer_type, axis=0)
# DataFrame with column names & new types
df_types = pd.DataFrame(df.apply(pd.api.types.infer_dtype, axis=0)).reset_index().rename(columns={'index': 'column', 0: 'type'})
自
推理规则与正常序列/数据帧构造期间的推理规则相同
考虑整数/浮点数例如:
df['amount']=pd.to_numeric(df['amount'],errors='ignore')
根据BeigeBruceWayne的答案
df_types = pd.DataFrame(df_final.apply(pd.api.types.infer_dtype, axis=0)).reset_index().rename(columns={'index': 'column', 0: 'type'})
loop_types = df_types.values.tolist()
for col in loop_types:
if col[1] == 'mixed':
pass
else:
if col[1] == 'decimal':
data_type = 'float64'
elif col[1] == 'string':
data_type = 'str'
elif col[1] == 'integer':
data_type = 'int'
elif col[1] == 'floating':
data_type = 'float64'
elif col[1] == 'date':
data_type = 'datetime64'
else:
data_type = col[1]
df_final[col[0]] = df_final[col[0]].astype(data_type)
谢谢。如何使用上述策略检查日期时间?
df['field\u name']=pd.to\u datetime(df['field\u name']))
仍然遇到同样的问题。列似乎可以同时作为datetime和float类型进行计算。等等,您是否正在尝试转换列以查看它是否会引发错误?您是否暗示您不知道数据列的类型?这很尴尬;我建议您先定义数据集。纪元时间中的日期可能类似于例如,转换为int或datetime都可以。是的,这是我的方法(代替更好的解决方案)…我不认为这是最好的方法,但我无法控制将读入数据帧的数据集(因此出现问题)。欢迎任何其他建议!!它被弃用真是太遗憾了。这是一个很好的方法。转换对象被is弃用not@itzjustricky推断对象甚至不会将['1',2',3']识别为数字.pd.DataFrame(['1',2',3'])。推断对象()。数据类型返回“object”似乎对我不起作用,返回所有字符串,即使有一些int、float和bool列
df_types = pd.DataFrame(df_final.apply(pd.api.types.infer_dtype, axis=0)).reset_index().rename(columns={'index': 'column', 0: 'type'})
loop_types = df_types.values.tolist()
for col in loop_types:
if col[1] == 'mixed':
pass
else:
if col[1] == 'decimal':
data_type = 'float64'
elif col[1] == 'string':
data_type = 'str'
elif col[1] == 'integer':
data_type = 'int'
elif col[1] == 'floating':
data_type = 'float64'
elif col[1] == 'date':
data_type = 'datetime64'
else:
data_type = col[1]
df_final[col[0]] = df_final[col[0]].astype(data_type)