将(行)函数应用于DataFrame会更改列类型 - python

列类型意外更改有问题,如下所示进行了精炼。 x列是浮点数,icol列是整数。当应用testfunction(不执行任何操作)时,列icol更改为类型float64,如以下代码所示:

df = pd.DataFrame({'x':[1000, -1000, 1.0]})       
df['icol'] = 1
print(df.dtypes)

def testfunction(r):
    pass
    return(r)
df = df.apply(testfunction, axis='columns')
print(df.dtypes)

但是,如果我同时将x和icol列都设置为整数,则类型不会更改。

df = pd.DataFrame({'x':[1000, -1000]})       
df['icol'] = 1
print(df.dtypes)

def testfunction(r):
    pass
    return(r)
df = df.apply(testfunction, axis='columns')
print(df.dtypes)

这是一种潜在的危害,例如,如果以后可能使用int列作为键,等等。

这是功能吗,还是我在这里做错了?在ubuntu上运行python 3.7.3

谢谢

参考方案

所有的Pandas运算都试图尽可能地提高数值效率。在对某行应用操作时,Pandas会尝试首先从该行构造一个Series。如果该行是整数和浮点数的混合,则将它们转换为浮点数,就像将混合列表传递给Series构造函数时一样:Series([1000.0, 1])转换为所有浮点数:即Series([1000.0, 1.0])

因此,如果您的行包含字符串,则使用object dtype,并且保留所有类型,但会降低性能。通常,应尽可能避免使用apply,并使用其他Pandas方法获取结果。

df = pd.DataFrame({'x':[1000, -1000, 1.0]})
df['y'] = 1
df['z'] = 'hello'

print(df.apply(testfunction, axis='columns').dtypes)
# prints:
x    float64
y      int64
z     object
dtype: object

在返回'Response'(Python)中传递多个参数 - python

我在Angular工作,正在使用Http请求和响应。是否可以在“响应”中发送多个参数。角度文件:this.http.get("api/agent/applicationaware").subscribe((data:any)... python文件:def get(request): ... return Response(seriali…

Python exchangelib在子文件夹中读取邮件 - python

我想从Outlook邮箱的子文件夹中读取邮件。Inbox ├──myfolder 我可以使用account.inbox.all()阅读收件箱,但我想阅读myfolder中的邮件我尝试了此页面folder部分中的内容,但无法正确完成https://pypi.python.org/pypi/exchangelib/ 参考方案 您需要首先掌握Folder的myfo…

R'relaimpo'软件包的Python端口 - python

我需要计算Lindeman-Merenda-Gold(LMG)分数,以进行回归分析。我发现R语言的relaimpo包下有该文件。不幸的是,我对R没有任何经验。我检查了互联网,但找不到。这个程序包有python端口吗?如果不存在,是否可以通过python使用该包? python参考方案 最近,我遇到了pingouin库。

Python ThreadPoolExecutor抑制异常 - python

from concurrent.futures import ThreadPoolExecutor, wait, ALL_COMPLETED def div_zero(x): print('In div_zero') return x / 0 with ThreadPoolExecutor(max_workers=4) as execut…

如何用'-'解析字符串到节点js本地脚本? - python

我正在使用本地节点js脚本来处理字符串。我陷入了将'-'字符串解析为本地节点js脚本的问题。render.js:#! /usr/bin/env -S node -r esm let argv = require('yargs') .usage('$0 [string]') .argv; console.log(argv…