Python函数更改不工作列的数据类型
我编写了一个python函数,用于接收数据帧的一列,检查数据类型,以及对所需数据类型的更改是否为false。但是,更改仅在函数内部发生。如何修复此问题以对数据帧进行永久性更改Python函数更改不工作列的数据类型,python,pandas,Python,Pandas,我编写了一个python函数,用于接收数据帧的一列,检查数据类型,以及对所需数据类型的更改是否为false。但是,更改仅在函数内部发生。如何修复此问题以对数据帧进行永久性更改 def change_required_data_type (column,data_type): is_correct = None for i in column: if type(i) != data_type: is_correct = False
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')
对于只在函数内部工作而不在函数外部工作的问题,需要在函数末尾添加return some object
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库,则应该使用常规方法更改列的数据类型。看
通常,您希望使用df.astype(str)
更改数据帧中一个或多个列的数据类型。数据帧的单列也称为序列
df['Column1'] = df['Column1'].astype('str')
df.Day = df.Day.astype('int64')
下面是在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')
的默认用法是返回副本,而不是替换原始数据帧。由于您已使用df.name=…
将更改分配给原始序列,因此您已更改了“就地”类型。您只是创建了一个新序列,当函数终止时,该序列将立即被丢弃。您从不修改传入的数据帧。顺便说一句,迭代一个系列并检查其中每个对象的类型没有多大意义,pandas的全部要点是要有类型化的列,因此您应该只检查列的.dtype
,我只为我的函数传入列。所以我需要修改它来传递数据帧,这将是一个开始