簡體   English   中英

根據不同列的部分字符串匹配在新數據框列中創建標簽

[英]create labels in a new data frame column based on partial string match of a different column

首先,我研究了許多SO線程,但似乎沒有一個能正常工作。 基於if-elif-else條件創建一個新列似乎與我正在嘗試的最接近。

在我的df中,我有一列包含產品名稱。 我正在嘗試創建一個函數,該函數在該列的每一行中查找部分字符串匹配項,並根據該匹配項為新df列中的每一行創建一個標簽。 我想使用一個函數,因為我需要匹配大約5或6個模式。

我正在使用contains()函數查找部分產品標題匹配。 這將返回一個布爾值,然后在函數中使用else / if進行檢查:

def label_sub_cat():
    if data['product'].str.contains('Proceedings', case=False) is True:
        return 'Proceedings'
    elif data['product'].str.contains('DVD', case=False) is True:
        return 'DVD'
    else:
        return 'Other'

data['product_sub_cat'] = data.apply(label_sub_cat(), axis=1)

我不斷收到以下錯誤:

AttributeError: 'DataFrame' object has no attribute 'other'

df.apply()中的函數應應用於df的每一行,而不是整個df。

In [37]: df = pd.DataFrame({'product':['aProcedings', 'aDVD','vcd']})
In [38]: def label_sub_cat(row):
...:     if 'Procedings' in row['product']:
...:         return 'Proceedings'
...:     elif 'DVD' in row['product']:
...:         return 'DVD'
...:     else:
...:         return 'Other'
...:
...:

In [39]: df['product_sub_cat'] = df.apply(label_sub_cat, axis=1)

In [40]: df
Out[40]:
       product product_sub_cat
0  aProcedings     Proceedings
1         aDVD             DVD
2          vcd           Other

只是改變你的功能

def label_sub_cat(row):
    if row.product.str.contains('Proceedings', case=False) is True:
        return 'Proceedings'
    elif row.product.str.contains('DVD', case=False) is True:
        return 'DVD'
    else:
        return 'Other'

data['product_sub_cat'] = data.apply(label_sub_cat, axis=1)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM