[英]How can I extract columns of data from a CSV file and define them as x and y variables, then plot them in python using pylab?
[英]How to Create Target(y) and X variables from CSV file
我正在閱讀 CSV 文件,出於建模目的,我需要創建目標 (Y) 和 X 變量。 不知道如何設置。 我是編碼新手,需要一些我似乎無法從 Pandas 文檔中理解的指導。 我希望將 Target 作為“Bad Indicator”,將“X”作為所有其他列。
import numpy as np
from scipy import stats
import matplotlib.pyplot as plt
import pandas as pd
project = pd.read_csv('c:/users/Brandon Thomas/Project.csv')
project=pd.DataFrame(project)
df = pd.DataFrame(project.data, columns = project.feature_names)
df["Bad Indicator"] = x.target
X = df.drop("Bad Indicator",axis=1) #Feature Matrix
y = df["Bad Indicator"] #Target Variable
df.head()
AttributeError Traceback (last last call last) in 1 # Build dataframe ----> 2 df = pd.DataFrame(project.data, columns = project.feature_names) 3 df["Bad Indicator"] = x.target 4 X = df.drop("Bad Indicator",axis=1) #Feature Matrix 5 y = df["Bad Indicator"] #目標變量
~\Anaconda3\lib\site-packages\pandas\core\generic.py in __getattr__(self,
name)
5065 if
self._info_axis._can_hold_identifiers_and_holds_name(name):
5066 return self[name]
-> 5067 return object.__getattribute__(self, name)
5068
5069 def __setattr__(self, name, value):
AttributeError: 'DataFrame' object has no attribute 'data'
在上面的代碼中,您創建一個 dataframe 3 次。 一次使用pd.read_csv
,一次使用project = pd.DataFrame(project)
,再一次使用df = pd.DataFrame(...)
。 默認情況下, pd.read_csv
object 將是 dataframe。
我已經刪除了當前不必要的導入,例如 numpy、scipy 和 matplotlib。 如果您以后需要它們,可以將它們添加回來。 要設置 Y 和 X,您需要做的就是:
import pandas as pd
df = pd.read_csv('c:/users/Brandon Thomas/Project.csv') # this will automatically name your columns if your csv has headers
#if your csv does not have headers:
df.columns = ['Bad Indicator', 'ColumnName1', 'ColumnName2',..]
X = df.drop("Bad Indicator",axis=1) #Feature Matrix
Y = df["Bad Indicator"] #Target Variable
df.head()
如果您的 csv 確實有標題,請刪除df.columns
行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.