【问题标题】:Filter rows based on contained strings then compare two columns in Python根据包含的字符串过滤行,然后比较 Python 中的两列
【发布时间】:2020-11-10 06:40:58
【问题描述】:

给定一个玩具数据集如下:

   id room_type company_name
0   1    office      ABC ltd
1   2    office       retail
2   3    office      xyz ltd
3   4    retail       retail
4   5   parking    toy store
5   6      hall          NaN

如果room_type 或company 列包含retail, parking or hall,则比较两列,如果它们不相同,则返回一个带有字符串Invalid company name or room type 的新列check。

我想使用如下代码,因为还有很多其他列要检查:

a = np.where(df['room_type'].str.contains('retail|parking|hall', na = False), 'Invalid company name or room type', None)

# b = np.where(df.area.str.contains('^\d+$', na = True), None,
#                                  'area is not a numbers')  
f = (lambda x: ';'.join(y for y in x if pd.notna(y)) 
                if any(pd.notna(np.array(x))) else np.nan )
df['check'] = [f(x) for x in zip(a)]

预期的结果是这样的:

   id room_type company_name                              check
0   1    office      ABC ltd                                NaN
1   2    office       retail  Invalid company name or room type
2   3    office      xyz ltd                                NaN
3   4    retail       retail                                NaN
4   5   parking    toy store  Invalid company name or room type
5   6      hall          NaN  Invalid company name or room type

如何修改条件a 代码?提前感谢您的帮助。

【问题讨论】:

    标签: python-3.x pandas string dataframe


    【解决方案1】:

    使用Series.str.cat 连接两列,测试子字符串和第二个条件比较Series.ne 不相等,最后一个链条件| 按位与:

    m1 = (df['room_type'].str.cat(df['company_name'], sep=' ', na_rep='')
                         .str.contains('retail|parking|hall', na = False))
    m2 = df['room_type'].ne(df['company_name'])
    
    df['check'] = np.where(m1 & m2, 'Invalid company name or room type', None)
    print(df)
       id room_type company_name                              check
    0   1    office      ABC ltd                               None
    1   2    office       retail  Invalid company name or room type
    2   3    office      xyz ltd                               None
    3   4    retail       retail                               None
    4   5   parking    toy store  Invalid company name or room type
    5   6      hall          NaN  Invalid company name or room type
    

    【讨论】:

    • 谢谢。顺便说一句,有没有办法突出显示有问题的单元格并将数据框保存为 excel 文件?
    • @ahbon - 不,没问题。例如,使用this 并将m = x['config_size_x'] != x['config_size_y'] 更改为m = x['check'].isna(),然后将df1.loc[m, ['config_size_x', 'config_size_y']] = c1 更改为df1.loc[m, :] = c1(可能: 应该省略)
    • 我发布一个新问题更合适,也许这个链接会有所帮助。 pandas.pydata.org/pandas-docs/stable/user_guide/style.html
    • @ahbon - 由你决定;)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-24
    • 1970-01-01
    • 2021-09-01
    • 2021-01-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多