【问题标题】:How implicitly determine dataframe column type in python? (implicit conversion)如何在python中隐式确定数据框列类型? (隐式转换)
【发布时间】:2021-05-21 23:59:41
【问题描述】:

在我的环境中,为了简单起见,决定将所有内容作为字符串存储在 hdfs 中。因此,当我从这个位置将数据拉入 pandas 数据框时,每种类型都是一个字符串,尽管值是整数、浮点数、布尔值等......

有没有办法根据值评估动态确定列属性类型?即:看看列中的每个值都是'x'类型,然后这样转换?

编辑:

由于我的 python 版本(我认为),我无法获得以下解决方案。所以我决定自己尝试一个hacky解决方案。这可能并不完美,我还没有确定日期。由于这两件事,我不会将其作为解决方案发布,但也许这可以成为其他需要它的人的起点:

#get dtypes when we can - Doesn't do dates. 
for i in df:
    try:
        df[i] = df[i].astype(int)
        print(i, 'is an int')
    except:
        []
    try:
        if '.' in str(df[i]):
            df[i] = df[i].astype(float)
            print(i, 'is a float')
    except:
        []
    
    try:
        if df[i].replace('False', '').unique()=='True' or df[i].replace('False', '').unique() == 'TRUE':
            df[i] = df[i].replace('False', '').astype(bool).astype(int)
            print(i, 'is bool')     
    except:
        print(i, 'is an object')

基本上,我只是在尝试强制转换并捕获错误(如果它中断)。不过,我确信这可能是一种非常糟糕的方法。

【问题讨论】:

    标签: python pandas types implicit-conversion


    【解决方案1】:

    我不知道有任何 pandas 内置功能可以做到这一点,但您可以使用 python ast.literal_eval 函数实现隐式转换。

    输入数据

    df = pd.DataFrame(np.array([['1', '0.3', 'True'],
                                 ['2', '5.2', 'False']]),
                       columns=['int', 'float', 'bool'])
    

    铸造功能

    def cast_df(df):
        for column in df.columns:
            if df[column].dtype != np.object:
                break
            column_types = df[column].apply(lambda x: type(ast.literal_eval(x)))
            if len(column_types.unique()) == 1:
                print(f"Column {column} is casted to {column_types[0]}")
                df[column] = df[column].astype(column_types[0])
        return df
    

    cast_df(df).dtypes 的输出:

    Column int is casted to <class 'int'>
    Column float is casted to <class 'float'>
    Column bool is casted to <class 'bool'>
    int        int64
    float    float64
    bool        bool
    dtype: object
    

    【讨论】:

    • 由于某种原因,这在我的 python 内核 3.5 pyspark 2.4 中不起作用。我在 ast.literal_eval 处不断收到错误
    猜你喜欢
    • 2013-07-09
    • 1970-01-01
    • 2021-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-21
    • 1970-01-01
    相关资源
    最近更新 更多