熊猫合并TypeError:“ NoneType”类型的对象没有len()

时间:2020-01-02 14:11:49

标签: python pandas

我有在BO 3系统上举行的在线锦标赛结果的列表。

基本上看起来像这样:

Player blue | Player red | Map 1 | Map 2 | Map 3
Player 1    | Player 2   | blue  | red   | red
Player 3    | Player 4   | blue  | blue  | N\A
Player 5    | Player 6   | blue  | red   | blue

以此类推。假设它包含3条记录

我想要实现的是

Player name | Won | lost | WR %
Player 1
player 2
Player 3 
Player 4 
Player 5
Player 6
总共

6条记录。我现在有一个包含一列并包含6个玩家的列表的df,但是,当我尝试将其与第一个df合并以计算输赢时,我收到TypeError:类型为'NoneType'的对象没有len()。 我在这里想念什么?

1 个答案:

答案 0 :(得分:0)

您可以尝试以下步骤:

  1. 使用meltmapwinner color转换为两列:
df = df.melt(id_vars=["Player blue", "Player red"],
              var_name="Map", value_name="Winner")
print(df)
#   Player blue Player red    Map Winner
# 0    Player 1   Player 2  Map 1   blue
# 1    Player 3   Player 4  Map 1   blue
# 2    Player 5   Player 6  Map 1   blue
# 3    Player 1   Player 2  Map 2    red
# 4    Player 3   Player 4  Map 2   blue
# 5    Player 5   Player 6  Map 2    red
# 6    Player 1   Player 2  Map 3    red
# 7    Player 3   Player 4  Map 3    N\A
# 8    Player 5   Player 6  Map 3   blue
  1. Player BluePlayer Red列执行相同的操作:
df = df.melt(id_vars=["Map", "Winner"],
             var_name="Color", value_name="Player")
print(df)
#       Map Winner        Color    Player
# 0   Map 1   blue  Player blue  Player 1
# 1   Map 1   blue  Player blue  Player 3
# 2   Map 1   blue  Player blue  Player 5
# 3   Map 2    red  Player blue  Player 1
# 4   Map 2   blue  Player blue  Player 3
# 5   Map 2    red  Player blue  Player 5
# 6   Map 3    red  Player blue  Player 1
# 7   Map 3    N\A  Player blue  Player 3
# 8   Map 3   blue  Player blue  Player 5
# 9   Map 1   blue   Player red  Player 2
# 10  Map 1   blue   Player red  Player 4
# 11  Map 1   blue   Player red  Player 6
# 12  Map 2    red   Player red  Player 2
# 13  Map 2   blue   Player red  Player 4
# 14  Map 2    red   Player red  Player 6
# 15  Map 3    red   Player red  Player 2
# 16  Map 3    N\A   Player red  Player 4
# 17  Map 3   blue   Player red  Player 6
  1. boolean作为获奖者(来源:ref
df['Won'] = df.apply(lambda x: x.Winner in x.Color, axis=1)
  1. 使用groupby
  2. 计算统计信息
def getStat(df):
    return pd.Series([sum(df.Won), sum(~df.Won), sum(df.Won)/df.shape[0]*100], index=["Won", "Lost", "WR (%)"])
df = df.groupby("Player").apply(getStat)
print(df)
#           Won  Lost     WR (%)
# Player
# Player 1  1.0   2.0  33.333333
# Player 2  2.0   1.0  66.666667
# Player 3  2.0   1.0  66.666667
# Player 4  0.0   3.0   0.000000
# Player 5  2.0   1.0  66.666667
# Player 6  1.0   2.0  33.333333

注意NA比赛被计算为两支球队的失败,请在步骤1之后随意删除NA行。