提问者:小点点

根据用户输入对数据帧列中的值进行计数


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

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

因此,如果用户输入“Maryland”,Python将返回“the number of occurrences in Maryland is 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)

共2个答案

匿名用户

给你:

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.loc[df['State'] == state_input, 'State'].count()
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

匿名用户

让我们像您所说那样创建一个数据帧

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 ]))