熊猫txt阅读和绘图的问题

时间:2019-07-24 23:35:22

标签: python python-3.x pandas dataframe

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

我的txt文件摘要...

package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "log"

    minerals "./minerals"
    srf "./srf"
)

func main() {

    //array of Test struct
    var SomeType [10]minerals.Test

    //Create 10 units of some random data to write
    for a := 0; a < 10; a++ {
        SomeType[a] = minerals.Test{
            Name:   "Rand",
            Id:     123,
            A:      "desc",
            Num:    999,
            Link:   "somelink",
            People: []string{"John Doe", "Aby Daby"},
        }
    }

    //writes aditional data to existing file, or creates a new file
    n, err := srf.WriteDataToFileAsJSON(SomeType, "test2.json")
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println("srf printed ", n, " bytes to ", "test2.json")

    //overrides previous file
    b, _ := json.MarshalIndent(SomeType, "", "\t")
    ioutil.WriteFile("test.json", b, 0644)

}

使用此代码,我将看到以下错误消息

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()

3 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

如果将read_csvheader=None一起使用,则熊猫将假定没有标题。您应该设置header=0来告诉熊猫,第一行包含标题。

docs有更多信息

答案 2 :(得分:0)

尝试以下代码,并通过在制表符中放置空格来设置.txt文件的格式

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

#Read_data

dataframe = pd.read_csv("./brain_body",delimiter="\t")
dataframe
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()
相关问题