【发布时间】:2017-11-06 18:43:46
【问题描述】:
我遇到了一个奇怪的问题,即在数据帧上按行使用 apply 函数不会保留数据帧中值的数据类型。有没有办法在保留原始数据类型的数据帧上逐行应用函数?
下面的代码演示了这个问题。如果在下面的 format 函数中没有 int(...) 转换,则会出现错误,因为数据帧中的 int 在传递到 func 时被转换为浮点数。
import pandas as pd
df = pd.DataFrame({'int_col': [1, 2], 'float_col': [1.23, 4.56]})
print(df)
print(df.dtypes)
def func(int_and_float):
int_val, float_val = int_and_float
print('int_val type:', type(int_val))
print('float_val type:', type(float_val))
return 'int-{:03d}_float-{:5.3f}'.format(int(int_val), float_val)
df['string_col'] = df[['int_col', 'float_col']].apply(func, axis=1)
print(df)
这是运行上述代码的输出:
float_col int_col
0 1.23 1
1 4.56 2
float_col float64
int_col int64
dtype: object
int_val type: <class 'numpy.float64'>
float_val type: <class 'numpy.float64'>
int_val type: <class 'numpy.float64'>
float_val type: <class 'numpy.float64'>
float_col int_col string_col
0 1.23 1 int-001_float-1.230
1 4.56 2 int-002_float-4.560
请注意,即使 df 的 int_col 列具有 dtype int64,当该列中的值传递到函数 func 时,它们突然具有 dtype numpy.float64,我必须使用 @987654332 @ 在函数的最后一行进行转换,否则该行会出错。
如有必要,我可以按这里的方式处理此问题,但我真的很想了解为什么会出现这种意外行为。
【问题讨论】: