2017-02-10 99 views
0

我試圖運行此代碼,但它返回這個錯誤Python的大熊貓「索引」對象有沒有屬性「海峽」

import pandas as pd 

df = pd.read_csv('olympics.csv', index_col=0, skiprows=1) 

for col in df.columns: 
    if col[:2]=='01': 
     df.rename(columns={col:'Gold'+col[4:]}, inplace=True) 
    if col[:2]=='02': 
     df.rename(columns={col:'Silver'+col[4:]}, inplace=True) 
    if col[:2]=='03': 
     df.rename(columns={col:'Bronze'+col[4:]}, inplace=True) 
    if col[:1]=='№': 
     df.rename(columns={col:'#'+col[1:]}, inplace=True) 

names_ids = df.index.str.split('\s\(') # split the index by '(' 

AttributeError: 'Index' object has no attribute 'str'

我該如何解決呢?我找不到它。

謝謝!

+0

df.index是numpy的陣列,而不是一個熊貓系列(因此不能使用該方法Series.str.split) – cmaher

+0

嘗試DF .index.to_series()。str.split('\ s \(') – Shijo

+0

Thank you!,it works! – cluna

回答

1

它解決了與(張貼在由@Shijo評論)

df.index.to_series().str.split('\s\(') 
+1

如果將'pandas'升級到最後一個版本'0.19.2',那麼'df.index.str.split '\ s \(')'起作用。 – jezrael