首页 > 解决方案 > 如何在python中的条件下过滤或提取或分组与其他2列进行比较的值列表

问题描述

我有一个 130 万行的 pandas 数据框和一组列,例如 Phone1(电话号码)、Sale_date(2015 年到 2020 年)、Product_description(185 个独特的产品描述)等。现在,我想过滤或提取 2020 年未购买任何产品(product_description 中的任何一种产品 - 比如说表格)的完整电话号码列表。

>>> data.info()**
<class 'pandas.core.frame.DataFrame'>
Int64Index: 1392125 entries, 0 to 1398844
Data columns (total 25 columns):
 #   Column            Non-Null Count    Dtype         
---  ------            --------------    -----                
 0   Sale_dt            1392125 non-null  datetime64[ns]             
 1   Phone1             1392125 non-null  object               
 2   prod_desc          1392125 non-null  object        
       
dtypes: datetime64[ns](1), object(2)
memory usage: 276.1+ MB

另一个问题是我的一些电话号码是科学计数法(9.96266e+09),而一些号码有特殊字符,例如044-4578930*** 如何将它们全部转换为电话号码格式?

当我确实尝试转换为 int 时,它会引发错误

数据['Phone1'].astype(int)

溢出错误:Python int 太大而无法转换为 C long

当我尝试时,

数据['Phone1'].astype('int64')

ValueError:int() 的无效文字,基数为 10:'22651435,9'

当我试图从电话号码中删除特殊字符时,

data.Phone1 = data.Phone1.str.replace('[^\d]+', '') 数据['Phone1']

数据['电话 1']

在此处输入图像描述

Out[52]: 
0          NaN
1          NaN
2          NaN
3          NaN
4          NaN
1398840    NaN
1398841    NaN
1398842    NaN
1398843    NaN
1398844    NaN
Name: Phone1, Length: 1392125, dtype: object

因此,我想对 2020 年没有购买过桌子(prod_desc 列中的产品之一)但他们本可以在前几年购买任何其他产品的电话号码进行分组或提取或过滤。那没关系。

请帮我解决这个问题。

标签: pythonpandasdataframefilterpandas-groupby

解决方案


推荐阅读