gpt4 book ai didi

python - pandas txt 读取和绘图的问题

转载 作者:行者123 更新时间:2023-12-01 00:43:03 25 4
gpt4 key购买 nike

我正在尝试使用 pandas 从 txt 文件中读取值并使用 matploitlib 绘制散点图,但在尝试不同的方法时我不断收到各种错误

我的 txt 文件的摘要...

Brain   Body         
0.37 0.117182754
73 1.349981613
70 0.925010921
0.8 0.007620352
0.15 0.001406136
50 0.419981176


from pandas import*
import pandas as pd
from sklearn import linear_model
import matplotlib.pyplot as plt

#Read_data

dataframe = pd.read_csv('./brain_body.txt' , header = None);
x_values = dataframe[['Brain']]
y_values = dataframe[['Body']]

#Training Model on data

body_reg = linear_model.LinearRegression()
body_reg.fit(x_values, y_values)


plt.scatter(x_values, y_values)
plt.plot(x_values, body_reg.predict(x_values))
plt.show()

使用这段代码,我得到了下面的错误消息

Traceback (most recent call last):
File "C:/Users/User/Documents/body_brain_prediction.py", line 9, in <module>
x_values = dataframe[['Brain']]
File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pandas\core\frame.py", line 2981, in __getitem__
indexer = self.loc._convert_to_indexer(key, axis=1, raise_missing=True)
File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pandas\core\indexing.py", line 1271, in _convert_to_indexer
return self._get_listlike_indexer(obj, axis, **kwargs)[1]
File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pandas\core\indexing.py", line 1078, in _get_listlike_indexer
keyarr, indexer, o._get_axis_number(axis), raise_missing=raise_missing
File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pandas\core\indexing.py", line 1163, in _validate_read_indexer
key=key, axis=self.obj._get_axis_name(axis)
KeyError: "None of [Index(['Brain'], dtype='object')] are in the [columns]"

最佳答案

您错误地认为文件中的数据以逗号分隔并且没有标题。事实上,它确实有标题并且是用空格分隔的。读取数据的正确方法如下:

dataframe = pd.read_csv('./brain_body.txt', sep=r'\s+')

关于python - pandas txt 读取和绘图的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57192499/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com