我想使用通用模式将函数应用于Pandas DataFrame中的每一列,但该函数应以列数据类型为条件。
听起来很简单。但是我在测试数据类型时发现了一种怪异的行为,无法在文档中找到任何地方或搜索其原因。
考虑这个repex:
import pandas as pd
toydf = pd.DataFrame(dict(
A = [1, 2, 3],
B = [1.1, 1.2, 1.3],
C = ['1', '2', '3'],
D = [True, True, False]
))
Run Code Online (Sandbox Code Playgroud)
分别检查它们是什么类型 dtype('int64'), dtype('float64'), dtype('O'), dtype('bool')
但是,如果我使用该apply函数,则传递给该函数的所有列都是dtype: object。
def dtype_fn(the_col):
print(the_col)
return(the_col.dtype)
toydf.apply(dtype_fn)
toydf.apply(dtype_fn)
0 1
1 2
2 3
Name: A, dtype: object
0 1.1
1 1.2
2 1.3
Name: B, dtype: object
0 1
1 2
2 3
Name: C, dtype: object
0 True
1 True
2 False
Name: D, dtype: object
Out[167]:
A object
B object
C object
D object
dtype: object
Run Code Online (Sandbox Code Playgroud)
为什么会这样?我做错了什么?为什么这些列不保留原始数据类型?
这是一种可行的方法,可以产生我想要的输出:(但是出于封装的原因,我不喜欢它)
def dtype_fn2(col_name):
return(toydf[col_name].dtype)
[dtype_fn2(col) for col in toydf.columns]
Out[173]: [dtype('int64'), dtype('float64'), dtype('O'), dtype('bool')]
Run Code Online (Sandbox Code Playgroud)
这个评论是正确的。此行为是设计使然。对于给定的所有dtype,Pandas“应用”在类型层次结构中最高的类型。
考虑仅将功能应用于“ A”,
df[['A']].apply(dtype_fn)
int64
A int64
dtype: object
Run Code Online (Sandbox Code Playgroud)
同样,只有“ A”和“ B”,
df[['A', 'B']].apply(dtype_fn)
float64
float64
A float64
B float64
dtype: object
Run Code Online (Sandbox Code Playgroud)
由于您有多种类型,包括原始DataFrame中的字符串,因此它们的通用类型都是object。
现在,这解释了该行为,但是我仍然需要解决此问题。熊猫提供了一种有用的方法:Series.infer_objects推断dtype并执行“软转换”。
如果您确实需要函数中的类型,则可以在调用之前执行软转换dtype。这将产生预期的结果:
def dtype_fn(the_col):
the_col = the_col.infer_objects()
print(the_col.dtype)
return(the_col.dtype)
Run Code Online (Sandbox Code Playgroud)
df.apply(dtype_fn)
int64
float64
object
bool
A int64
B float64
C object
D bool
dtype: object
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
304 次 |
| 最近记录: |