熊猫,尝试拆分数据时收到“ TypeError:'列表'对象不可调用”

有一些看起来像这样的数据:

Name        Best Rating
Player1     97.1% (FS)
Player2     96.3% (CB)
Player3     95.5% (DR)
Player4     95.4% (DL)

我正在尝试拆分列,以便它看起来像这样:

Name        Max Rating        Best Position
Player1     97.1              FS
Player2     96.3              CB
Player3     95.5              DR
Player4     95.4              DL

我的代码如下所示:

import pandas as pd
df = pd.read_csv('prem1.csv', sep = ";", encoding = 'unicode_escape')

cols = ['Max Rating', 'Best Position']   
df['Best Rating'].str.split('% ', expand=True).rename(columns = cols)
df.head()

当我尝试此代码时,出现以下错误消息:

TypeError: 'list' object is not callable

Here is a more detailed explanation of the error code (screenshot). https://imgur.com/vbGswh9

关于这里出什么问题以及为什么我无法拆分列的任何想法?

评论
  • ksed
    ksed 回复

    pandas.DataFrame.rename requires a callable or mapper for the columns parameter. Typically, a dict will do.

    尝试以下方法:

    df['Best Rating'].str.split('% ', expand=True).rename(columns = {k: v for k, v in enumerate(col))
    

    或者,如果您想更明确:

    cols = {0: 'Max Rating', 1: 'Best Position'}
    df['Best Rating'].str.split('% ', expand=True).rename(columns = cols)