禁止显示警告Python Pandascolab_noteb

2024-04-25 14:07:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试将pandas df中的三位数国家代码列规范化。我发现了一个很好的函数country_converter,目前我正在一个非常大的数据帧中的country列上运行这个函数。因为列中存在NaN值,所以它返回这些警告的数千。在

WARNING:root:nan not found in ISO3

我在找两样东西:

  1. 具体地抑制nan警告
  2. 为了加快这个函数的处理时间(我的想法是抑制警告应该加快进程,但是,如果你有任何建议尝试不同的东西与我的代码,那将是伟大的!在

我试过这个名字的所有变体,但似乎都不管用,所以我想我遗漏了一些东西。。。在

import country_converter as coco
import pandas as pd
import numpy as np
import warnings

warnings.filterwarnings("ignore", message= "nan not found in ISO3")
warnings.filterwarnings("ignore", message= "root:nan not found in ISO3")
warnings.filterwarnings("ignore", message= "WARNING:root:nan not found in ISO3")

test = pd.DataFrame({"code":[np.nan, 'XXX', 'USA', 'GBR', "GBR",'SWE/n', "123", "abs", "ABCC", "ABC", np.nan, np.nan]})


test['code_convert']= test["code"].apply(lambda x: coco.convert(names= x, to='ISO3', not_found= np.NaN))

预期不会再看到带有nan值的警告。在


Tags: 函数inimport警告asnpnotroot
1条回答
网友
1楼 · 发布于 2024-04-25 14:07:03

我已经调整了数据帧中的数据,使np.nan公司适当的np.nan公司而不是字符串。在

test = pd.DataFrame(
    {
        "code": [
            np.nan,
            "XXX",
            "USA",
            "GBR",
            "GBR",
            "SWE/n",
            "123",
            "abs",
            "ABCC",
            "ABC",
            np.nan,
            np.nan,
        ]
    }
)

print(test)

     code
0     NaN
1     XXX
2     USA
3     GBR
4     GBR
5   SWE/n
6     123
7     abs
8    ABCC
9     ABC
10    NaN
11    NaN

然后你要做的就是过滤掉np.nan公司当你计算的时候。在

^{pr2}$

我没有安装国家/地区转换器,但如果我简化了“应用于测试”:

test["code_convert"] = test[test.notna()].apply(
    lambda x: x + "_solution"
)

print(test)

     code    code_convert
0     NaN             NaN
1     XXX    XXX_solution
2     USA    USA_solution
3     GBR    GBR_solution
4     GBR    GBR_solution
5   SWE/n  SWE/n_solution
6     123    123_solution
7     abs    abs_solution
8    ABCC   ABCC_solution
9     ABC    ABC_solution
10    NaN             NaN
11    NaN             NaN

相关问题 更多 >

    热门问题