Skip to main content
 首页 » 编程设计

python之在 Pandas 中加入数据框

2024年10月01日14kuangbin

我收到错误:

TypeError: 'method' 对象不可订阅

当我尝试连接两个 Pandas 数据框时...

看不出他们有什么问题!

有关信息,请执行 Kaggle 泰坦尼克号问题:

titanic_df.head() 
Out[102]: 
Survived    Pclass  SibSp   Parch   Fare    has_cabin   C   Q   title   Person 
0   0   3   1   0   7.2500  1   0.0 0.0 Mr  male 
1   1   1   1   0   71.2833 0   1.0 0.0 Mrs female 
2   1   3   0   0   7.9250  1   0.0 0.0 Miss    female 
3   1   1   1   0   53.1000 0   0.0 0.0 Mrs female 
4   0   3   0   0   8.0500  1   0.0 0.0 Mr  male 
In [103]: 
 
sns.barplot(x=titanic_df["Survived"],y=titanic_df["title"]) 
Out[103]: 
<matplotlib.axes._subplots.AxesSubplot at 0x11b5edb00> 
 
In [125]: 
 
title_dummies=pd.get_dummies(titanic_df["title"]) 
title_dummies=title_dummies.drop([" Don"," Rev"," Dr"," Col"," Capt"," Jonkheer"," Major"," Mr"],axis=1) 
title_dummies.head() 
Out[125]: 
Lady    Master  Miss    Mlle    Mme Mrs Ms  Sir the Countess 
0   0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 
1   0.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 
2   0.0 0.0 1.0 0.0 0.0 0.0 0.0 0.0 0.0 
3   0.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 
4   0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 
In [126]: 
 
titanic_df=title_dummies.join[titanic_df] 
--------------------------------------------------------------------------- 
TypeError                                 Traceback (most recent call last) 
<ipython-input-126-a0e0fe306754> in <module>() 
----> 1 titanic_df=title_dummies.join[titanic_df] 
 
TypeError: 'method' object is not subscriptable 

请您参考如下方法:

您需要在 DataFrame.join 中将 [] 更改为 ()功能:

titanic_df=title_dummies.join(titanic_df) 
print (titanic_df) 
   Lady  Master  Miss  Mlle  Mme  Mrs   Ms  Sir  the  Countess  Survived  \ 
0     0     0.0   0.0   0.0  0.0  0.0  0.0  0.0  0.0       0.0         0    
1     1     0.0   0.0   0.0  0.0  0.0  1.0  0.0  0.0       0.0         1    
2     2     0.0   0.0   1.0  0.0  0.0  0.0  0.0  0.0       0.0         1    
3     3     0.0   0.0   0.0  0.0  0.0  1.0  0.0  0.0       0.0         1    
4     4     0.0   0.0   0.0  0.0  0.0  0.0  0.0  0.0       0.0         0    
 
   Pclass  SibSp  Parch     Fare  has_cabin    C    Q title  Person   
0       3      1      0   7.2500          1  0.0  0.0    Mr    male   
1       1      1      0  71.2833          0  1.0  0.0   Mrs  female   
2       3      0      0   7.9250          1  0.0  0.0  Miss  female   
3       1      1      0  53.1000          0  0.0  0.0   Mrs  female   
4       3      0      0   8.0500          1  0.0  0.0    Mr    male