使用 numpy 的复杂之处在于有两个错误来源(以及要阅读的文档),即 python 本身以及 numpy。
我相信您的问题是您正在使用所谓的structured (numpy) array。
考虑以下示例:
>>> import numpy as np
>>> a = np.array([(1,2), (4,5)], dtype=[('Game 1', '<f8'), ('Game 2', '<f8')])
>>> a.sum()
TypeError: cannot perform reduce with flexible type
现在,我首先选择我要使用的数据:
>>> import numpy as np
>>> a = np.array([(1,2), (4,5)], dtype=[('Game 1', '<f8'), ('Game 2', '<f8')])
>>> a["Game 1"].sum()
5.0
这正是我想要的。
也许您会考虑使用pandas(python 库),或者将语言更改为R。
个人意见
尽管“numpy”确实是一个强大的库,但我仍然避免将它用于数据科学和其他程序围绕“灵活”数据类型设计的“活动”。就我个人而言,当我需要一些快速且可维护的东西时(很容易编写“面向未来的代码”),我会使用 numpy,但我没有时间编写 C 程序。
就 Pandas 而言,它对我们“Python 黑客”来说很方便,因为它是“用 Python 实现的 R 数据结构”,而“R”(显然)是一种全新的语言。我个人使用 R,因为我认为 Pandas 正在快速发展,这使得编写“考虑未来的代码”变得困难。
正如评论中所建议的(我相信@jorijnsmit),对于“简单”的情况,不需要引入大的依赖项,例如熊猫。下面的简约示例同时兼容 Python 2 和 3,它使用“典型”Python 技巧来处理问题数据。
import csv
## Data-file
data = \
'''
, Game1, Game2, Game3, Game4, Game5
Player1, 2, 6, 5, 2, 2
Player2, 6, 4 , 1, 8, 4
Player3, 8, 3 , 2, 1, 5
Player4, 4, 9 , 4, 7, 9
'''
# Write data to file
with open('data.csv', 'w') as FILE:
FILE.write(data)
print("Raw data:")
print(data)
# 1) Read the data-file (and strip away spaces), the result is data by column:
with open('data.csv','rb') as FILE:
raw = [ [ item.strip() for item in line] \
for line in list(csv.reader(FILE,delimiter=',')) if line]
print("Data after Read:")
print(raw)
# 2) Convert numerical data to integers ("float" would also work)
for (i, line) in enumerate(raw[1:], 1):
for (j, item) in enumerate(line[1:], 1):
raw[i][j] = int(item)
print("Data after conversion:")
print(raw)
# 3) Use the data...
print("Use the data")
for i in range(1, len(raw)):
print("Sum for Player %d: %d" %(i, sum(raw[i][1:])) )
for i in range(1, len(raw)):
print("Total points in Game %d: %d" %(i, sum(list(zip(*raw))[i][1:])) )
输出将是:
Raw data:
, Game1, Game2, Game3, Game4, Game5
Player1, 2, 6, 5, 2, 2
Player2, 6, 4 , 1, 8, 4
Player3, 8, 3 , 2, 1, 5
Player4, 4, 9 , 4, 7, 9
Data after Read:
[['', 'Game1', 'Game2', 'Game3', 'Game4', 'Game5'], ['Player1', '2', '6', '5', '2', '2'], ['Player2', '6', '4', '1', '8', '4'], ['Player3', '8', '3', '2', '1', '5'], ['Player4', '4', '9', '4', '7', '9']]
Data after conversion:
[['', 'Game1', 'Game2', 'Game3', 'Game4', 'Game5'], ['Player1', 2, 6, 5, 2, 2], ['Player2', 6, 4, 1, 8, 4], ['Player3', 8, 3, 2, 1, 5], ['Player4', 4, 9, 4, 7, 9]]
Use the data
Sum for Player 1: 17
Sum for Player 2: 23
Sum for Player 3: 19
Sum for Player 4: 33
Total points in Game 1: 20
Total points in Game 2: 22
Total points in Game 3: 12
Total points in Game 4: 18