Skip to main content
 首页 » 编程设计

python之简单数据集 regplot 中的 keyerror之AttributeError : 'str' object has no attribute 'conjugate'

2025年02月15日9over140

我正在创建此数据:

import numpy as np 
import pandas as pd 
import matplotlib.pyplot as plt 
import seaborn as sns 
sns.set() 
 
data = np.array([['', 'Gross ', 'Target'], 
                 [0, 728, 500], 
                 [1, 701, 750], 
                 [2, 590, 570], 
                 [3, 548, 596]]) 
 
df = pd.DataFrame(data=data[1:, 1:], columns=data[0, 1:]) 
df 
 
    Gross   Target 
0   728     500 
1   701     750 
2   590     570 
3   548     596 

并尝试绘制:

sns.regplot(x='Gross', y='Target', data=df) 

结果:KeyError: 'Gross'

---更新---

修复空白后,我收到:

AttributeError: 'str' 对象没有属性 'conjugate'

请您参考如下方法:

字符串中有空格,转为列:

print (df.columns.tolist()) 
['Gross ', 'Target'] 

一个可能的解决方案是 strip :

df.columns = df.columns.str.strip() 
print (df.columns.tolist()) 
['Gross', 'Target'] 

或者在列名中添加空格:

sns.regplot(x='Gross ', y='Target', data=df) 

print (df.dtypes) 
Gross     object 
Target    object 
dtype: object 
 
sns.regplot(x='Gross', y='Target', data=df.astype(int))