【问题标题】:Use values of a dictionary to label a column with keys of dicrtionary in Python在 Python 中使用字典的值用字典的键标记列
【发布时间】:2021-12-21 18:45:43
【问题描述】:
data = {'Name':['Tom', 'nick', 'krish', 'jack'],
        'Note':['The color is red', 'This is a white blouse', 'I love the blue hoodie', 'What is that orange box?']}
  
# Create DataFrame
df = pd.DataFrame(data)

这是我的数据集 DF。我想在“注意”列中找到一些颜色词,所以我创建了一个字典,所有值都是我要搜索的颜色词。然后我想创建一个返回字典键的新列。

F={'One':'red','Two':'white', 'Three':'blue', 'Four':'orange'}

我想在 for 循环中执行此操作,但它不起作用。似乎 y 参数在被赋值后不再被替换。有人可以建议吗?谢谢!

for i in range(4):
    print(list(F.values())[i])
    df['C']=np.where(df['Note'].str.contains(list(F.values())[i]), list(F.keys())[i], 
                          )

【问题讨论】:

  • 想要的输出是什么?
  • 想要的数据框是:df=pd.DataFrame{'Name':['Tom', 'nick', 'krish', 'jack'], 'Note':['颜色是red', 'This is a white blouse', '我喜欢蓝色连帽衫', '那个橙色盒子是什么?'], 'C':['One', 'Two', 'Three', 'Four'] }
  • 在下面查看我的答案。

标签: python dictionary for-loop


【解决方案1】:

如果我理解正确,您需要:

df['Match'] = df['Note'].replace({f'.*{v}.*': k for k, v in F.items()}, regex=True)

现在:

>>> df
    Name                      Note  Match
0    Tom          The color is red    One
1   nick    This is a white blouse    Two
2  krish    I love the blue hoodie  Three
3   jack  What is that orange box?   Four
>>> 

或者如果你只想替换单词:

df['Match'] = df['Note'].replace({v: k for k, v in F.items()}, regex=True)

输出:

>>> df
    Name                      Note                    Match
0    Tom          The color is red         The color is One
1   nick    This is a white blouse     This is a Two blouse
2  krish    I love the blue hoodie  I love the Three hoodie
3   jack  What is that orange box?   What is that Four box?
>>>

【讨论】:

  • 谢谢!这就是我要找的
猜你喜欢
  • 2022-10-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多