如何在数据帧中发现数据类型错误?

2024-04-23 11:28:40 发布

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

df1型:

  product   product_Id   Price
0 Mobile      G67129     4500
1 Earphone    H56438     8900
2 Heater      K12346     fgdht
3 Kitchen     566578     4500
4 4359        Gh1907     5674
5 plastic     G67129     Dfz67

df2型:

  Column_Name   Expected_Dtype
0 product          String
1 product_Id       String
2 Price            int

我需要从df1中找出数据类型错误值,并且在df2中有列数据类型信息。你知道吗

输出:

   column_Name  Value  Exp_dtype index
0  product       4359  String    4
1  product_Id   566578 String    3
2  Price       fgdht    int      2
3  Price       Dfz67    int      5

Tags: nameidstringproductmobilepriceint数据类型
1条回答
网友
1楼 · 发布于 2024-04-23 11:28:40

由于这些类型混合在一起,都是object,所以我只能考虑使用str match和regex模式来识别错误类型。你知道吗

以下是我的解决方案:

首先查找具有错误类型的行

bad_product = df['product'].loc[df['product'].str.match(r'[0-9.]+')]
bad_product_ID = df.product_Id.loc[df['product_Id'].str.match(r'[0-9.]+')]
bad_price = df.Price.loc[~df['Price'].str.match(r'[0-9.]+')]

将所有错误行合并在一起

df3 = pd.concat([bad_product,bad_product_ID,bad_price], axis=1).stack().reset_index()
df3.columns = ['index', 'Column_Name', 'value']

与df2合并

df2.set_index('Column_Name')
df3.set_index('Column_Name')
result = pd.merge(df3, df2, how='left')

结果:


  index Column_Name value   Expected_Dtype
0   2   Price       fgdht   int
1   3   product_Id  566578  String
2   4   product     4359    String
3   5   Price       Dfz67   int

当你不知道如何开始时,试着把它分解成一个小任务。希望这会有帮助。你知道吗

相关问题 更多 >