Python函数更改列的数据类型不起作用

时间:2019-07-08 01:28:35

标签: python pandas

我编写了一个python函数来接收数据帧的一列,检查数据类型,以及是否对所需的数据类型进行了错误的更改。但是,更改仅在函数内发生。如何解决此问题以对数据框进行永久更改?

def change_required_data_type (column,data_type):
    is_correct = None

    for i in column:
        if type(i) != data_type:
            is_correct = False


    if is_correct != False:
        print('True')

    elif is_correct == False:
        column = column.astype(data_type)        
        print('False')

1 个答案:

答案 0 :(得分:1)

对于仅在函数内部起作用而不在外部起作用的问题,您需要在函数的末尾添加返回某些对象

def myfunc(column, data_type):
    # ...
    elif is_correct == False:
    column = column.astype(data_type)        
    print('False')

    # You've modified the column variable inside the function,
    # so your function needs to return it to outside the function.        
    return column

# Call your function from outside.
result = myfunc(column, data_type)  
# Use inputs for column and data_type when calling your function.
print(result)

但是,如果使用的是Pandas库,则应使用常规方法来更改列的数据类型。参见https://cmdlinetips.com/2018/09/how-to-change-data-type-for-one-or-more-columns-in-pandas-dataframe/

通常,您要使用df.astype(str)来更改Pandas数据框中一列或多列的数据类型。数据框的单列也称为系列。

df['Column1'] = df['Column1'].astype('str')
df.Day = df.Day.astype('int64')

还有更多在Pandas DataFrame对象中更改数据类型的示例。

import pandas as pd

mydic = {
    "name": ['Alice', 'Tommy', 'Jane'],
    "age": [9, 21, 22],
    "height": [3.6, 6.1, 5.5],
}

df = pd.DataFrame(data = mydic)
print(df)
print(df.dtypes)

# First change age from integer to floating point.
df.age = df.age.astype('float64')

print(df.age)  # Notice the decimal format 9.0.
print(df.dtypes)  # age is now floating point.

# Next change height from floating point to integer.
df.height = df.height.astype('int32')
print(df.height)  # Notice height is truncated, no more decimal point.

# Next change age to string (object type).
df.age = df.age.astype('str')
print(df.dtypes)
print(df)

# Change height from integer to float, using Bracket Notation.
df['height'] = df['height'].astype('float32')
print(df.dtypes)
# Notice height is a decimal format, 3.0.
# But the original fractional data of .6 was lost (was 3.6).

df.astype('str')的默认用法是返回COPY,而不替换原始数据帧。因为您已经使用df.name = ...将更改分配给了原始系列,所以您更改了“就地”类型。