Skip to main content
 首页 » 编程设计

python之将浮点列转换为字符串并测试字符串在 Pandas 中的存在

2025年05月04日25youxin

我有这个数据框:

   cnpj             Porte 
0  453232000125  
1  11543123000156 
2  345676 
3  121234561023456 

'cnpj' 当前是 float 的。

如果 cnpj 中有 '0001',我想将 'Porte' 分类为 A。所以它看起来像这样:

   cnpj             Porte 
0  453232000125     A 
1  11543123000156   A 
2  345676 
3  121234561023456 

我正在尝试:

 df['Porte'].loc[(df['cnpj'].astype(int).astype(str).str.contains('0001'))]='A' 

但它给我带来了这个错误:

TypeError: cannot convert the series to <class 'int'> 

我该怎么做?

请您参考如下方法:

这是一种方法。

演示:

import pandas as pd 
import numpy as np 
df = pd.DataFrame({"cnpj": [453232000125, 11543123000156, 345676]}) 
df["Porte"] = df["cnpj"].apply(lambda x: "A" if '0001' in str(x) else np.nan) 
print(df) 

输出:

             cnpj Porte 
0    453232000125     A 
1  11543123000156     A 
2          345676   NaN