Python 迭代每一行,并增加csv文件中与特定研究者相关的术语的计数

Python 迭代每一行,并增加csv文件中与特定研究者相关的术语的计数,python,pandas,numpy,Python,Pandas,Numpy,我正在阅读python中的一个csv文件,其中一列有许多疾病名称,另一列有相关研究人员。文件看起来像这样- [Table 1] Terms Researcher 1.Asthma Dr. Roberts 2.Brochial cancer Dr. Lee 3.HIV Dr.Roberts 4.HIV Dr. Lee 5.Influenza

我正在阅读python中的一个csv文件,其中一列有许多疾病名称,另一列有相关研究人员。文件看起来像这样-

[Table 1]
Terms                    Researcher
1.Asthma                 Dr. Roberts
2.Brochial cancer        Dr. Lee
3.HIV                    Dr.Roberts
4.HIV                    Dr. Lee
5.Influenzae             Dr. Wang
6.Bronchial Cancer       Dr. Wang
7.Influenzae             Dr. Roberts
8.dengue                 prof. christopher
9.Arthritis              prof. swaminathan
10.Arthritis             prof. christopher
11.Asthma                Dr. Roberts
12.HIV                   Dr. Lee
13.Bronchial Cancer      Dr. Wang
14.dengue                prof. christopher
15.HIV                   prof. christopher
16.HIV                   Dr. Lee
Term you are looking for : HIV
Names of the researchers                Frequency
Dr. Roberts                             1
Dr. Lee                                 3
prof. christopher                       1
我希望我的代码遍历每一行,并增加与每个研究人员相关的术语的频率计数,以便当用户输入他/她正在寻找的术语时,他们应该得到如下输出表-

[Table 1]
Terms                    Researcher
1.Asthma                 Dr. Roberts
2.Brochial cancer        Dr. Lee
3.HIV                    Dr.Roberts
4.HIV                    Dr. Lee
5.Influenzae             Dr. Wang
6.Bronchial Cancer       Dr. Wang
7.Influenzae             Dr. Roberts
8.dengue                 prof. christopher
9.Arthritis              prof. swaminathan
10.Arthritis             prof. christopher
11.Asthma                Dr. Roberts
12.HIV                   Dr. Lee
13.Bronchial Cancer      Dr. Wang
14.dengue                prof. christopher
15.HIV                   prof. christopher
16.HIV                   Dr. Lee
Term you are looking for : HIV
Names of the researchers                Frequency
Dr. Roberts                             1
Dr. Lee                                 3
prof. christopher                       1
现在让我们看看我在做什么-

In[1]:
import pandas as pd
import numpy as np
data = pd.read_csv("Researchers Title Terms.csv")
data.head()
这给了我[表1] 然后我就这样做了-

In[2]:
term = input("Enter the term you are looking for:")
term = term.lower()
list_of_terms = []
for row in data: 
    if row[data.Terms] == term
        researcher1 += 1

    elif data.Terms == term
        researcher2 += 1

    elif data.Terms == term
        researcher3 += 1

    else
        print("Sorry!", term, "not found in the database!")
print("Term you are looking for : ", term)
print("Dr. Roberts:", researcher1)
print("Dr. Lee:", researcher2)
print("prof. christopher:", researcher3)
我在这里得到的只是-

File "<ipython-input-9-b85d0d187059>", line 5
if row[data.Terms] == term
                          ^
SyntaxError: invalid syntax
文件“”,第5行
如果行[data.Terms]==术语
^
SyntaxError:无效语法
我是python编程的初学者,所以不太确定我的逻辑是否完全错误,或者这里确实存在一些语法错误。任何帮助都将不胜感激。在尝试了一些事情,但没有得到任何结果后,我把这件事推到了社区上。
提前谢谢

在Python中,当创建if、elif、for循环等时,正确的语法是在初始化行的末尾有一个冒号。因此,在您的代码中,您需要将其更新为以下内容:

from collections import Counter
from pprint import pprint

if __name__ == '__main__':
    docs = ["Dr.Roberts",
            "Dr.Lee",
            "Dr.Roberts",
            "Dr.Lee",
            "Dr.Wang",
            "Dr.Wang",
            "Dr.Roberts",
            "prof.christopher",
            "prof.swaminathan",
            "prof.christopher",
            "Dr.Roberts",
            "Dr.Lee",
            "Dr.Wang",
            "prof.christopher",
            "prof.christopher",
            "Dr.Lee"]
    pprint(Counter(docs).most_common(5))
    for row in data: 
        if row[data.Terms] == term:
            researcher1 += 1

        elif data.Terms == term:
            researcher2 += 1

        elif data.Terms == term:
            researcher3 += 1

        else:
            print("Sorry!", term, "not found in the database!")

而且,一旦你纠正了这个错误,基于你的代码,你看起来也会有一个bug。您正在将用户输入设置为小写,但对从CSV文件读取的数据不执行相同的操作。因此,所有术语都不等于用户输入。

在Python中,当创建if、elif、for循环等时。正确的语法是在初始化行的末尾有一个冒号。因此,在您的代码中,您需要将其更新为以下内容:

    for row in data: 
        if row[data.Terms] == term:
            researcher1 += 1

        elif data.Terms == term:
            researcher2 += 1

        elif data.Terms == term:
            researcher3 += 1

        else:
            print("Sorry!", term, "not found in the database!")

而且,一旦你纠正了这个错误,基于你的代码,你看起来也会有一个bug。您正在将用户输入设置为小写,但对从CSV文件读取的数据不执行相同的操作。因此,所有术语都不等于用户输入。

将数据读入熊猫。接受输入,然后过滤,
groupby
&
size
给出所需的结果

term = input("Enter the term you are looking for:")

data[data.Term.str.lower() == term.lower()].groupby('Researcher').size()
# Output with term = 'HIV'
Dr. Lee              3
Dr.Roberts           1
prof. christopher    1
dtype: int64
在该方法中,未显示与某个术语(即,have size==0)无关的研究人员

要显示没有计数为零的项的研究人员,首先设置一个研究人员的数据框,并将结果数据框与其连接

researchers = pd.DataFrame({'Researcher': data.Researcher.unique()})
out = data[data.Term.str.lower() == term.lower()].groupby('Researcher').agg({'Terms': 'size'})
pd.merge(reserachers, out, how='outer').fillna(0).sort_values('Terms', ascending=False)
# outputs:
          Researcher  Terms
1            Dr. Lee    3.0
2         Dr.Roberts    1.0
4  prof. christopher    1.0
0        Dr. Roberts    0.0
3           Dr. Wang    0.0
5  prof. swaminathan    0.0

将数据读入熊猫。接受输入,然后过滤,
groupby
&
size
给出所需的结果

term = input("Enter the term you are looking for:")

data[data.Term.str.lower() == term.lower()].groupby('Researcher').size()
# Output with term = 'HIV'
Dr. Lee              3
Dr.Roberts           1
prof. christopher    1
dtype: int64
在该方法中,未显示与某个术语(即,have size==0)无关的研究人员

要显示没有计数为零的项的研究人员,首先设置一个研究人员的数据框,并将结果数据框与其连接

researchers = pd.DataFrame({'Researcher': data.Researcher.unique()})
out = data[data.Term.str.lower() == term.lower()].groupby('Researcher').agg({'Terms': 'size'})
pd.merge(reserachers, out, how='outer').fillna(0).sort_values('Terms', ascending=False)
# outputs:
          Researcher  Terms
1            Dr. Lee    3.0
2         Dr.Roberts    1.0
4  prof. christopher    1.0
0        Dr. Roberts    0.0
3           Dr. Wang    0.0
5  prof. swaminathan    0.0

您可以使用与正在执行的操作类似的方式迭代数据帧,但由于您使用的是
pandas
,因此可能值得利用
pandas
函数。它们通常比迭代快得多,代码最终看起来更干净

term_of_interest = 'HIV'

(df.groupby('Researcher')
 .apply(lambda x: x.Terms.str.contains(term_of_interest)
        .sum())
 .rename('Frequency').to_frame())

                   Frequency
Researcher                  
Dr. Lee                    3
Dr. Roberts                0
Dr. Wang                   0
Dr.Roberts                 1
prof. christopher          1
prof. swaminathan          0

您可以使用与正在执行的操作类似的方式迭代数据帧,但由于您使用的是
pandas
,因此可能值得利用
pandas
函数。它们通常比迭代快得多,代码最终看起来更干净

term_of_interest = 'HIV'

(df.groupby('Researcher')
 .apply(lambda x: x.Terms.str.contains(term_of_interest)
        .sum())
 .rename('Frequency').to_frame())

                   Frequency
Researcher                  
Dr. Lee                    3
Dr. Roberts                0
Dr. Wang                   0
Dr.Roberts                 1
prof. christopher          1
prof. swaminathan          0
groupby
value\u计数
简单直观

df.Terms = df.Terms.str.replace('\d+\.\s*', '').str.upper()
df.Researcher = df.Researcher.str.title()
s = df.groupby('Terms').Researcher.value_counts()

s

Terms             Researcher       
ARTHRITIS         Prof. Christopher    1
                  Prof. Swaminathan    1
ASTHMA            Dr. Roberts          2
BROCHIAL CANCER   Dr. Lee              1
BRONCHIAL CANCER  Dr. Wang             2
DENGUE            Prof. Christopher    2
HIV               Dr. Lee              3
                  Dr.Roberts           1
                  Prof. Christopher    1
INFLUENZAE        Dr. Roberts          1
                  Dr. Wang             1
Name: Researcher, dtype: int64
您可以使用
loc
xs

s.loc['HIV']

Researcher
Dr. Lee              3
Dr.Roberts           1
Prof. Christopher    1
Name: Researcher, dtype: int64


pd.factorize
np.bincount
您可以使用与上述相同的方式访问。

groupby
value\u counts
简单直观

df.Terms = df.Terms.str.replace('\d+\.\s*', '').str.upper()
df.Researcher = df.Researcher.str.title()
s = df.groupby('Terms').Researcher.value_counts()

s

Terms             Researcher       
ARTHRITIS         Prof. Christopher    1
                  Prof. Swaminathan    1
ASTHMA            Dr. Roberts          2
BROCHIAL CANCER   Dr. Lee              1
BRONCHIAL CANCER  Dr. Wang             2
DENGUE            Prof. Christopher    2
HIV               Dr. Lee              3
                  Dr.Roberts           1
                  Prof. Christopher    1
INFLUENZAE        Dr. Roberts          1
                  Dr. Wang             1
Name: Researcher, dtype: int64
您可以使用
loc
xs

s.loc['HIV']

Researcher
Dr. Lee              3
Dr.Roberts           1
Prof. Christopher    1
Name: Researcher, dtype: int64


pd.factorize
np.bincount

您可以使用与上面相同的方式访问。

如果行[data.Terms]==term:
您也缺少
elif
的冒号。
如果行[data.Terms]==term:
您也缺少
elif
的冒号。效果非常好!非常感谢。唯一的问题是我想从用户那里获取输入,只列出用户想要查找的术语。用户输入的单词保存在我的变量“term”中。所以我尝试--'s.loc(term)'而不仅仅是's',但将其作为输出--您能帮我吗?整个代码-
term=input(“输入您要查找的术语:”)term=term.lower()data.Terms=data.Terms.str.replace('\d+\.\s*,'')).str.upper()data.Author=data.Author.str.title()s=data.groupby('Terms').Author.value\u counts()/n s.loc(term)
工作起来很有魅力!非常感谢。唯一的问题是我想从用户那里获取输入,只列出用户想要查找的术语。用户输入的单词保存在我的变量“term”中。所以我尝试--'s.loc(term)'而不仅仅是's',但将其作为输出--您能帮我吗?整个代码-
term=input(“输入您要查找的术语:”)term=term.lower()data.Terms=data.Terms.str.replace('\d+\.\s*','').str.upper()data.Author=data.Author.str.title()s=data.groupby('Terms').Author.value\u counts()/n s.loc(term)