【问题标题】:check if key is present in the row as a substring检查键是否作为子字符串存在于行中
【发布时间】:2021-05-05 10:26:18
【问题描述】:

我有一本字典

myDict = {
'apple': 'FULL FORM',
'ball' : 'NEW'
}

然后是一个数据框:

myCol
..
new apple
netball
hello

我想遍历 col myCol 的所有行以及我的字典的所有键,以查看我的任何键是否作为行值中的子字符串存在。如果是,我想获取键值并将其附加到列表中。例如,键值'apple'作为我的第一行'new apple'中的子字符串出现,所以我想提取键值'apple'

我正在尝试这个,但迭代似乎不起作用,因为我得到了所有“未找到”

myList = []
for index, row in df.iterrows():
        for key, value in myDict.items():  
            if key in row['myCol'].lower():
                mylist.append(key)
        else:
            print(row['myCol'].lower())
            mylist.append('Not Found')
print(mylist) 

【问题讨论】:

    标签: python python-3.x pandas dataframe data-analysis


    【解决方案1】:

    您的解决方案应该更改为break:

    myList = []
    for index, row in df.iterrows():
            for key, value in myDict.items():  
                if key in row['myCol'].lower():
                    myList.append(key)
                    break
            else:
                print(row['myCol'].lower())
                myList.append('Not Found')
    print(myList) 
    ['apple', 'ball', 'Not Found']
    

    或者使用Series.str.extract by keys of dictionary with join by | for regex or,如果没有匹配生成缺失值,则将其替换为Series.fillna并将Series转换为列表:

    myList = (df['myCol'].str.extract(f'({"|".join(myDict.keys())})', expand=False, case=False)
                         .fillna('Not Found')
                         .tolist())
    
    print(myList) 
    ['apple', 'ball', 'Not Found']
    

    【讨论】:

      猜你喜欢
      • 2012-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-16
      • 1970-01-01
      • 1970-01-01
      • 2020-07-06
      • 1970-01-01
      相关资源
      最近更新 更多