【发布时间】:2018-09-10 10:12:06
【问题描述】:
我一直在尝试遍历 pandas 数据框中的字符串以查找特定的单词集,在这里我成功了。
但是,我意识到我不仅要查找单词,还要查看单词的语义并将一组与我的主要关键字具有相同含义的单词组合在一起。
我偶然发现了以下问题 How to return key if a given string matches the keys value in a dictionary,这正是我想要做的,但不幸的是无法让它在 pandas 数据框中工作。
以下是可以在链接中找到的解决方案之一:
my_dict = {"color": ("red", "blue", "green"), "someothercolor":("orange", "blue", "white")}
solutions = []
my_color = 'blue'
for key, value in my_dict.items():
if my_color in value:
solutions.append(key)
输出:
color
我的数据框:
现在我有一个数据框,我想遍历 df['Name'] 以找到一个值,然后我想将键添加到新列。在此示例中,它将是 df['Colour']
+---+----------+--------------------------+-----------------------------+----------+--------+
| | SKU | Name | Description | Category | Colour |
+---+----------+--------------------------+-----------------------------+----------+--------+
| 0 | 7E+10 | Red Lace Midi Dress | Red Lace Midi D... | Dresses | |
| 1 | 7E+10 | Long Armed Sweater Azure | Long Armed Sweater Azure... | Sweaters | |
| 2 | 2,01E+08 | High Top Ruby Sneakers | High Top Ruby Sneakers... | Shoes | |
| 3 | 4,87E+10 | Tight Indigo Jeans | Tight Indigo Jeans... | Denim | |
| 4 | 2,2E+09 | T-Shirt Navy | T-Shirt Navy... | T-Shirts | |
+---+----------+--------------------------+-----------------------------+----------+--------+
预期结果:
+---+----------+--------------------------+-----------------------------+----------+--------+
| | SKU | Name | Description | Category | Colour |
+---+----------+--------------------------+-----------------------------+----------+--------+
| 0 | 7E+10 | Red Lace Midi Dress | Red Lace Midi D... | Dresses | red |
| 1 | 7E+10 | Long Armed Sweater Azure | Long Armed Sweater Azure... | Sweaters | blue |
| 2 | 2,01E+08 | High Top Ruby Sneakers | High Top Ruby Sneakers... | Shoes | red |
| 3 | 4,87E+10 | Tight Indigo Jeans | Tight Indigo Jeans... | Denim | blue |
| 4 | 2,2E+09 | T-Shirt Navy | T-Shirt Navy... | T-Shirts | blue |
+---+----------+--------------------------+-----------------------------+----------+--------+
我的代码:
colour = {'red': ('red', 'rose', 'ruby’), ‘blue’: (‘azure’, ‘indigo’, ’navy')}
def fetchColours(x):
for key, value in colour.items():
if value in x:
return key
else:
return np.nan
df['Colour'] = df['Name'].apply(fetchColours)
我收到以下错误:
TypeError: 'in <string>' requires string as left operand, not tuple
我无法针对字符串运行元组。我该如何处理?
【问题讨论】:
标签: python pandas string dataframe dictionary