python – 无法使用灵活类型执行reduce

前端之家收集整理的这篇文章主要介绍了python – 无法使用灵活类型执行reduce前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我有这个数据集:

  1. Game1 Game2 Game3 Game4 Game5
  2. Player1 2 6 5 2 2
  3. Player2 6 4 1 8 4
  4. Player3 8 3 2 1 5
  5. Player4 4 9 4 7 9

我想为每个玩家计算5场比赛的总和.

这是我的代码

  1. import csv
  2. f=open('Games','rb')
  3. f=csv.reader(f,delimiter=';')
  4. lst=list(f)
  5. lst
  6. import numpy as np
  7. myarray = np.asarray(lst)
  8. x=myarray[1,1:] #First player
  9. y=np.sum(x)

我有错误“无法使用灵活类型执行缩减”.我真的很陌生,我需要你的帮助.

谢谢

最佳答案
考虑使用Pandas module

  1. import pandas as pd
  2. df = pd.read_csv('/path/to.file.csv',sep=';')

结果DataFrame:

  1. In [196]: df
  2. Out[196]:
  3. Game1 Game2 Game3 Game4 Game5
  4. Player1 2 6 5 2 2
  5. Player2 6 4 1 8 4
  6. Player3 8 3 2 1 5
  7. Player4 4 9 4 7 9

和:

  1. In [197]: df.sum(axis=1)
  2. Out[197]:
  3. Player1 17
  4. Player2 23
  5. Player3 19
  6. Player4 33
  7. dtype: int64
  8. In [198]: df.sum(1).values
  9. Out[198]: array([17,23,19,33],dtype=int64)

猜你在找的Python相关文章