我遇到了一个奇怪的问题,即apply在数据帧上按行使用函数不会保留数据帧中值的数据类型。有没有办法在保留原始数据类型的数据帧上逐行应用函数?
下面的代码演示了这个问题。如果没有在下面int(...)的format函数中进行转换,就会出现错误,因为数据帧中的 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)
Run Code Online (Sandbox Code Playgroud)
以下是运行上述代码的输出:
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
Run Code Online (Sandbox Code Playgroud)
请注意,即使 的int_col列df具有 dtype int64,当来自该列的值传递给 function 时func,它们突然具有 dtype numpy.float64,我必须int(...)在函数的最后一行使用转换回来,否则该行会出错。
如有必要,我可以按照我在这里的方式处理这个问题,但我真的很想了解为什么我会看到这种意外行为。
Mic*_*ael 10
您的整数越来越upcasted成浮动。如果可能,Pandas(和 NumPy)将尝试将 Series(或 ndarray)转换为单一数据类型。据我所知,没有记录向上转换的确切规则,但是您可以通过使用numpy.find_common_type.
您可以通过在调用 apply 之前将 DataFrame 转换为“Object”类型来诱使 Pandas 和 NumPy 保持原始数据类型,如下所示:
df['string_col'] = df[['int_col', 'float_col']].astype('O').apply(func, axis=1)
Run Code Online (Sandbox Code Playgroud)
让我们分解一下这里发生的事情。首先,在我们执行之后 df 会发生什么.astype('O')?
as_object = df[['int_col', 'float_col']].astype('O')
print(as_object.dtypes)
Run Code Online (Sandbox Code Playgroud)
给出:
int_col object
float_col object
dtype: object
Run Code Online (Sandbox Code Playgroud)
好的,现在两列都具有相同的数据类型,即对象。我们从之前知道apply()(或从 DataFrame 中提取一行的任何其他内容)将尝试将两列转换为相同的 dtype,但它会看到它们已经相同,所以没有什么可做的。
但是,我们仍然能够获得原始整数和浮点数,因为它dtype('O')表现为某种可以容纳任何 Python 对象的容器类型。通常,当 Series 包含不应混合的类型(如字符串和整数)或任何 NumPy 不理解的 Python 对象时,会使用它。
| 归档时间: |
|
| 查看次数: |
2049 次 |
| 最近记录: |