【问题标题】:How can I count instances of a string in a dataframe column of lists that matches the string of a column in a different dataframe?如何计算列表的数据框列中与不同数据框中的列字符串匹配的字符串实例?
【发布时间】:2023-01-29 21:30:19
【问题描述】:

我有一个数据框,其中包含一列农产品和一列农产品的颜色列表:

import pandas as pd

data = {'produce':['zucchini','apple','citrus','banana','pear'],
      'colors':['green, yellow','green, red, yellow','orange, yellow ,green','yellow','green, yellow, brown']}
df = pd.DataFrame(data)
print(df)

数据框看起来像:

    produce                 colors
0  zucchini          green, yellow
1     apple     green, red, yellow
2    citrus  orange, yellow, green
3    banana                 yellow
4      pear   green, yellow, brown

我正在尝试用每种颜色创建第二个数据框,并计算第一个数据框中具有该颜色的列数。我能够将唯一的颜色列表放入数据框中:

#Create Dataframe with a column of unique values
unique_colors = df['colors'].str.split(",").explode().unique()
df2 = pd.DataFrame()
df2['Color'] = unique_colors
print(df2)

但是有些颜色有时会重复:

     Color
0    green
1   yellow
2      red
3   orange
4    green
5   yellow
6    brown

而且我无法找到一种方法来添加一个列来计算另一个数据框中的实例。我努力了:

#df['Count'] = data['colors'] == df2['Color']
df['Count'] = ()
for i in df2['Color']:
      count=0
      if df["colors"].str.contains(i):
            count+1
      df['Count']=count

但我收到错误“ValueError:值的长度 (0) 与索引的长度 (5) 不匹配”

我怎么能够

  1. 确保列表中的值不重复,并且
  2. 计算其他数据框中颜色的实例

    (这是一个更大的数据框的简化,所以我不能只编辑第一个数据框中的值来修复独特的颜色问题)。

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    拆分时需要考虑,周围的空间。要计算颜色出现的次数,可以使用Series.value_counts()

    out = (df['colors'].str.split(' *, *')
           .explode().value_counts()
           .to_frame('Count')
           .rename_axis('Color')
           .reset_index())
    
    print(out)
    
        Color  Count
    0  yellow      5
    1   green      4
    2     red      1
    3   brown      1
    4  orange      1
    

    【讨论】:

      【解决方案2】:

      建议脚本

      import operator
      
      y_c = (df['colors'].agg(lambda x: [e.strip() for e in x.split(',')])
                         .explode()
             )
      
      clrs = pd.DataFrame.from_dict({c: [operator.countOf(y_c, c)] for c in y_c.unique()})
      

      结果的两个演示

      1 - 水平:

      print(clrs.rename(index={0:'count'}))
      
      #        green  yellow  red  orange  brown
      # count      4       5    1       1      1
      

      2- 垂直 :

      print(clrs.T.rename(columns={0:'count'}))
      
      #         count
      # green       4
      # yellow      5
      # red         1
      # orange      1
      # brown       1
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-07-10
        • 2020-10-23
        • 2018-12-29
        • 1970-01-01
        • 2023-01-18
        • 2021-11-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多