首页 > 解决方案 > 考虑到字符串 [with str.contains] 在 python 中的位置,计算行数并创建标签列

问题描述

我有以下数据框:

df = pd.DataFrame([["1", "shirt is blue", True, "Feb"],
                   ["2", "blue shirt with green stripes", False, "March"],
                   ["3", "shirt is green", True, "Feb"],
                   ["4", "shirt is light-green", True, "Feb"],
                   ["5", "shirt is light-green", True, "Feb"],
                   ["6", "blue shirt", True, "March"],
                   ["7", "shirt shirt shirt", False, "March"],
                   ["8", "green shirt with dark-blue stripes", False, "Feb"],
                   ["9", "shirt is blue with red stripes", False, "March"],
                   ["10", "shirt is a red shirt", False, "Feb"]],
                  columns=["id", "text", "cond", "month"])

我想计算(稍后绘制图表)每种颜色(蓝色、绿色和红色)的衬衫有多少。

尝试了这样的过滤器:

 blue = df[df['text'].str.contains('blue',case=False)]
 green = df[df['text'].str.contains('green',case=False)]
 red = df[df['text'].str.contains('red',case=False)]

第一个问题: 有没有更聪明的方法来做到这一点(如循环,而不是每种颜色的线)?

第二个(也是更重要的)问题: 我应该将“带有绿色条纹的蓝色衬衫”视为蓝色衬衫,但是当我使用上面的代码时,句子中“颜色”的顺序根本不计算在内,所以我使用此文本获得蓝色计数和绿色计数。

在像示例这样的情况下,我怎样才能只为蓝色获得一个计数?

重要的是要注意句子中出现的第一种颜色始终是“主要”颜色。

那么,我该如何正确地做到这一点,即考虑到字符串的位置来计算行数?(或者也许我应该考虑十字路口?)

解决上述问题后,我还想添加一个新列:

df['color'] = 'NaN'
df['color'] = np.where((df['id'].isin(blue['id'])),'Blue',df.color)
df['color'] = np.where((df['id'].isin(green['id'])),'Green',df.color)
df['color'] = np.where((df['id'].isin(red['id'])),'Red',df.color)
df['color'] = df['color'].str.replace('NaN', 'Other', regex=True)

与第一个问题一样,有什么方法可以更聪明地做到这一点?

标签: pythonpandasstringdataframe

解决方案


如果第一种颜色是“主要的”,您可以使用.str.extract. 它将从文本中提取第一个匹配项:

df["color"] = df["text"].str.extract(r"(red|green|blue)")
print(df)

印刷:

   id                                text   cond  month  color
0   1                       shirt is blue   True    Feb   blue
1   2       blue shirt with green stripes  False  March   blue
2   3                      shirt is green   True    Feb  green
3   4                shirt is light-green   True    Feb  green
4   5                shirt is light-green   True    Feb  green
5   6                          blue shirt   True  March   blue
6   7                   shirt shirt shirt  False  March    NaN
7   8  green shirt with dark-blue stripes  False    Feb  green
8   9      shirt is blue with red stripes  False  March   blue
9  10                shirt is a red shirt  False    Feb    red

推荐阅读