我正在阅读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
现在让我们看看我在做什么-
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
我是python编程的初学者,所以不太确定我的逻辑是完全错误的还是这里确实存在一些语法错误。任何帮助都将不胜感激。在尝试了一些事情,但没有得到任何结果后,我把这个放在了社区上。 提前谢谢!你知道吗
在Python中,当创建if、elif、for循环等时,正确的语法是在初始化行的末尾有一个冒号。因此,在您的代码中,您需要将其更新为以下内容:
而且,一旦你纠正了这个问题,基于你的代码,你看起来也会有一个bug。您正在将用户输入设置为小写,但对从CSV文件读取的数据没有执行相同的操作。因此,没有一个术语能与用户输入相等。你知道吗
groupby
和value_counts
简单直观
您可以使用
loc
或xs
访问各种术语或者
pd.factorize
和np.bincount
您可以使用与上述相同的方式访问。你知道吗
您可以用与您所做的类似的方式迭代数据帧,但是由于您使用的是
pandas
,因此值得利用pandas
函数。它们通常比迭代快得多,代码最终看起来更干净。你知道吗相关问题 更多 >
编程相关推荐