我将以下数据存储在csv文件中
id x y name
312 33.76 55.2 aaa
312 33.76 55.2 aaa
443 66.33 11.5 ccc
686 44.55 ddd
222 44.6 eee
423 88.3 23.6 fff
我使用以下代码来查找受欢迎程度 popular = dict(Counter(数据[' id'])) 打印" id \ tpopularity"
for k, v in popularity.items():
print '{0:.0f}\t{1}'.format(k,v)
我找到了使用此代码的唯一ID
uni_id = np.unique(data['id'])
现在我想打印出x,y和流行度的唯一ID,但没有名称,需要忽略没有x或y的列
像这样: id x y popularity
312 33.76 55.2 2
443 66.33 11.5 1
423 88.3 23.6 1
答案 0 :(得分:0)
这应该可以,但它没有经过测试:
import csv
class Row(object):
def __init__(self, id, x, y, name):
self.id = id
self.x = x
self.y = y
self.name = name
column_names = [] # here lies first row from csv file
rows = [] # list of Row-class objects
file = None # file we loaded
with open("filename.csv", newline='') as f:
file = csv.reader(f, delimiter=',') # this loads csv file and splits it by
# '' as newline and ',' as data seperator
# file is now table full of data looking like this:
# [[id, x, y, name], [312, 33.76, 55.2, 'aaa'],...]
columns_names = file[:1] # first row of file are column names
file = file[1:] # slicing our list
for row in file:
rows.append(Row(row[0], row[1], row[2], row[3])) # creating Row-class objects
print(column_names)
for row in rows:
print(("%s %s %s %s" % (row.id, row.x, row.y, row.name))
此代码显示如何加载和解析csv文件。您现在需要的是在if
循环中添加几个for
状态,以忽略包含x
或y
数据的行。
可能你需要阅读classes