【问题标题】:Counting the values in a dataframe column based on user input根据用户输入计算数据框列中的值
【发布时间】:2020-06-22 14:49:50
【问题描述】:

我正在尝试根据用户输入计算我的数据框列中出现的次数:

ID   State        Comments
1    California   Outsourced
2    Maryland     NA
3    Maryland     Outsourced

因此,如果用户输入“马里兰州”,Python 将返回“马里兰州的出现次数为 2”。我在网上找不到答案,所以我尝试这样做:

state_input = input("Enter the state: ")
while True:
    if state_input == df['State']:
       df['State'].eq(state_input).sum()
    break
if cases > 0:
    print(cases)

【问题讨论】:

    标签: python loops dataframe input count


    【解决方案1】:

    给你:

    import pandas as pd
    from io import StringIO
    
    df = pd.read_csv(StringIO("""ID   State        Comments
    1    California   Outsourced
    2    Maryland     NA
    3    Maryland     Outsourced"""), sep='\s+')
    
    state_input = input("Enter the state: ")
    cases = (df['State'] == state_input).sum()
    if cases:
        print(f"The number of occurrences in {state_input} is {cases}")
    

    输出:

    Enter the state: Maryland
    The number of occurrences in Maryland is 2
    

    【讨论】:

      【解决方案2】:

      让我们像你说的那样创建一个数据框

      import pandas as pd
      dic = {'ID':[1,2,3],'State':['California','Maryland','Maryland'], 'Comments':['Outsourced','NA','Outsourced']}
      df = pd.DataFrame(dic)
      df
      

      这可能会有所帮助

      state_input = input("Enter the state: ")
      
      if state_input in df.State.values:
          print(len(df[df['State'] == state_input ]))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-08-11
        • 1970-01-01
        • 2015-02-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多