Python 无法对csv文件进行分组和合计
我创建了一个csv文件,其中有两列“作者”和“图书数量”-请参见示例(下面的“抱歉”看起来不像一个表格,但第1列有作者,第2列在本图中只有数字1) 我正在尝试创建一个输出csv,对作者ie Vincent 5、Thomas 3和Jimmy 2的书进行汇总 使用下面的代码,我成功地进入了中间阶段,在这个阶段我得到了每个作者的累计总数。行Python 无法对csv文件进行分组和合计,python,python-2.7,Python,Python 2.7,我创建了一个csv文件,其中有两列“作者”和“图书数量”-请参见示例(下面的“抱歉”看起来不像一个表格,但第1列有作者,第2列在本图中只有数字1) 我正在尝试创建一个输出csv,对作者ie Vincent 5、Thomas 3和Jimmy 2的书进行汇总 使用下面的代码,我成功地进入了中间阶段,在这个阶段我得到了每个作者的累计总数。行打印行[0],countAuthor生成正确的 Vincent 1 Vincent 2 Vincent 3 Vincent 4 Thomas 1 Thomas
打印行[0],countAuthor
生成正确的
Vincent 1
Vincent 2
Vincent 3
Vincent 4
Thomas 1
Thomas 2
Thomas 3
Jimmy 1
Jimmy 2
然后我计划将此输出放入一个列表,按降序排序,只保留具有最高值的记录,即当前作者与前一作者相同的位置,然后跳过-然后将输出写入另一个csv文件
我的问题是,我无法将作者和累计总数写入一个列表,我可以将其写入变量w<代码>打印w[2]有效,但打印数据[2]无效,因为数据似乎只有一列。任何帮助都将不胜感激,因为我花了将近两天的时间在这个问题上,运气不好——我被迫使用csv,因为完整的文件中有作者姓名和空格等
with open("testingtesting6a.csv") as inf:
data = []
author = 'XXXXXXXX'
countAuthor = 0.0
for line in inf:
line = line.split(",")
if line[0] == author:
countAuthor = countAuthor + float(line[1])
else:
countAuthor = float(line[1])
author = line[0]
# print line[0], countAuthor
w = (line[0],line[1],countAuthor)
print w[2]
data.append(w)
print data[2]
# print data[0]
# print type(w)
# print w[2]
标准库已经涵盖了这一点
import collections
def sum_up(input_file):
counter = collections.defaultdict(int)
for line in input_file:
parts = line.split() # splits by any whitespace.
if len(parts) != 2:
continue # skip the line that does not parse; maybe a blank line.
name, number = parts
counter[name] += int(number) # you can't borrow 1.25 books.
return counter
现在您可以:
with open('...') as f:
counts = sum_up(f)
for name, count in sorted(counts.items()):
print name, count # prints counts sorted by name.
print counts['Vincent'] # prints 4.
print counts['Jane'] # prints 0.
这里的诀窍是使用,一个假装对任何键都有值的dict。我们要求它具有由int()
生成的默认值,即0。使用strip
删除空格,使用Pandas删除groupby:
输入文件(附加空格是有意的):
你能举一个你想打印的数据的例子吗?因为在我看来,你想要像{'Vincent':5,'Thomas':3,'Jimmy':2}这样的东西,
打印数据[2]
会打印出什么呢?谢谢你回复我,伙计们,我输入打印数据[2]只是为了向自己证明数据没有3列数据[2]返回了索引错误-我们期望的输出我想要Vincent,托马斯,3岁,詹姆斯,4感谢那些人——我试了你的建议。当我找到名称number=linesplit()时,我收到一条错误消息“Value error需要不止一个值才能解包”是否有不包含两个值的行?作业假设正好有两个。请参阅更新。
with open('...') as f:
counts = sum_up(f)
for name, count in sorted(counts.items()):
print name, count # prints counts sorted by name.
print counts['Vincent'] # prints 4.
print counts['Jane'] # prints 0.
author,books
Vincent, 1
Vincent , 1
Vincent, 1
Vincent, 1
Thomas , 1
Thomas, 1
Thomas, 1
Jimmy, 1
Jimmy , 1
import csv
import pandas as pd
fin = open('author.csv', 'r')
reader = csv.DictReader(fin, delimiter=',')
# strip remove spaces
authors=[( (d['author']).strip(), int((d['books']).strip())) for d in reader]
df = pd.DataFrame(authors)
df.columns = ['author', 'books']
df2 = (df.groupby('author').sum())
print (df2)
books
author
Jimmy 2
Thomas 3
Vincent 4
# For total of books:
print (df2.books.sum())
9