简体   繁体   English

如果名称是空字符串,如何重命名Pandas DataFrame列?

[英]How to rename a Pandas DataFrame column if the name is an empty string?

I've imported an HTML table from Basketball Reference using pandas, but I'm running into an annoyance trying to rename a couple of columns that have empty strings for their name. 我使用pandas从Basketball Reference导入了一个HTML表格,但是我正在努力重命名几个列为空名字符串的列。

Here's the code to pull the table: 这是拉表的代码:

tables = pd.read_html('http://www.basketball-reference.com/leagues/NBA_2016_games.html')
games = tables[0]

The columns look like this: 列看起来像这样:

Out[138]: 

Index([u'Date', u'Start (ET)', u'Visitor/Neutral', u'PTS', u'Home/Neutral',
       u'PTS.1', u' ', u' .1', u'Notes'],
       dtype='object')

Renaming everything except for the u' ' and u' .1' columns is no issue, but I cannot find the right way to rename the empty ones using a label approach. 重命名除了u' 'u' .1'列之外的所有内容都没有问题,但我找不到使用标签方法重命名空列的正确方法。

I tried this by default (limited to renaming only a few columns here): 我默认尝试了这个(仅限于在这里重命名几列):

column_names = {'Date': 'date', ' ': 'box', ' .1': 'overtime'}
games.rename(columns = column_names)

but this leaves the ' ' and ' .1' columns unchanged. 但这会使' '' .1'' .1'列保持不变。

This method works: 此方法有效:

column_names = {games.columns[6]: 'box', games.columns[7]: 'overtime'}

But is there any way to change these names without explicitly referencing the position? 但有没有办法在没有明确引用位置的情况下更改这些名称?

也许这可能是一个快速修复 - 明确设置列名称。

df.columns = [u'Date', u'Start (ET)', u'Visitor/Neutral', u'PTS', u'Home/Neutral', u'PTS.1', u'Rename1', u'Rename2', u'Notes']

For me works add str.strip for remove trailing whitespaces, also is necessary change dict values (remove whitespaces): 对我来说,工程添加str.strip来删除尾随空格,也是必要的更改dict值(删除空格):

column_names = {'Date': 'date', '': 'box', '.1': 'overtime'}
games.columns = games.columns.str.strip()
games = games.rename(columns = column_names)
print (games.columns)
Index(['date', 'Start (ET)', 'Visitor/Neutral', 'PTS', 'Home/Neutral', 'PTS.1',
       'box', 'overtime', 'Notes'],
      dtype='object')

Another solution is export column names to list and there is \\xa ( NO-BREAK SPACE ): 另一种解决方案是导出列名list并且有\\xaNO-BREAK SPACE ):

print (games.columns.tolist())
['Date', 'Start (ET)', 'Visitor/Neutral', 'PTS', 'Home/Neutral', 
 'PTS.1', '\xa0', '\xa0.1', 'Notes']


column_names = {'Date': 'date', '\xa0': 'box', '\xa0.1': 'overtime'}
games = games.rename(columns = column_names)
print (games.columns)
Index(['date', 'Start (ET)', 'Visitor/Neutral', 'PTS', 'Home/Neutral', 'PTS.1',
       'box', 'overtime', 'Notes'],
      dtype='object')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM