Python Pandas推断列数据类型

Cal*_*ari 10 python profiling pandas

我正在将JSON文件读入数据帧.数据框可能包含一些String(对象)类型列,一些Numeric(int64和/或float64)以及一些日期时间类型列.读入数据时,数据类型通常不正确(即datetime,int和float通常存储为"object"类型).我想报告这种可能性.(即列在数据帧中为"object"(String),但它实际上是"datetime").

我遇到的问题是,当我使用pd.to_numericpd.to_datetime时,他们将评估并尝试转换列,并且很多次它最终取决于我最后调用的两个中的哪一个...(我打算使用convert_objects()可以使用,但是这是折旧的,所以想要一个更好的选择).

我用来评估数据帧列的代码是(我意识到下面的很多内容是多余的,但为了便于阅读,我已经用这种方式编写了代码):

try:
   inferred_type = pd.to_datetime(df[Field_Name]).dtype
   if inferred_type == "datetime64[ns]":
      inferred_type = "DateTime"
except:
   pass
try:
   inferred_type = pd.to_numeric(df[Field_Name]).dtype
   if inferred_type == int:
      inferred_type = "Integer"
   if inferred_type == float:
      inferred_type = "Float"
except:
   pass
Run Code Online (Sandbox Code Playgroud)

Pab*_*rre 8

我遇到了同样的问题,必须找出传入数据的列类型,其中类型事先未知(从我的案例中读取的数据库)。我在 SO 上或通过查看 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
Run Code Online (Sandbox Code Playgroud)


小智 6

在 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'})
Run Code Online (Sandbox Code Playgroud)

http://pandas.pydata.org/pandas-docs/stable/ generated/pandas.api.types.infer_dtype.html#pandas.api.types.infer_dtype

自从

推理规则与正常的 Series/DataFrame 构造期间相同。

考虑int/floats 的to_numeric
例如:df['amount'] = pd.to_numeric(df['amount'], errors='ignore')

  • 似乎对我不起作用,返回所有字符串,即使有一些 int、float 和 bool 列 (8认同)

小智 5

This worked best for me:

    df.convert_dtypes()
Run Code Online (Sandbox Code Playgroud)


小智 0

尝试例如

df['field_name'] = df['field_name'].astype(np.float64)
Run Code Online (Sandbox Code Playgroud)

(假如说import numpy as np