機器學習之pandas常用函式筆記

2021-09-19 23:50:08 字數 2154 閱讀 2289

import pandas as pd

food_info=pd.read_csv("food_info.csv")

###將資料傳入。指定檔名即可。使用相對路徑。

print(type(food_info))

###將資料通過pandas傳入,pandas的資料結構就是dataframe

print(food_info)
print(food_info.dtypes)

###檢視資料的結構

###字元值是object的結構

print(help(pd.read_csv))

##檢視幫助文件。當不知道函式如何使用的時候。

food_info.head()

###使用head()把資料前五行顯示,在預設情況下。

food_info.head(3)

###把資料的前3條顯示一下。

###列印資料的列名。

print(food_info.columns)

##列印矩陣的維度

print(food_info.shape)

###取資料,例子中將第乙個資料拿到手。

print(food_info.loc[0])

###取資料的切片。

food_info.loc[3:6]

###一列一列的取資料,肢解通過列名取資料。

ndb_col =food_info["ndb_no"]

print(ndb_col)

###這個例子是拿到的ndb_no列的資料。

####也可以將列名賦值給變數通過變數來取出列名

col_name = "ndb_no"

print(food_info[col_name])

###d定位兩列。

###將這兩個列組成list結構。然後將這兩個列作為變數傳入就可以了。

print(food_info.columns)

columns = [ 'water_(g)', 'energ_kcal']

print(food_info[columns])

####查詢一某些字元結尾

col_names = food_info.columns.tolist()

###將字元型的資料轉換成list型的資料。

print(col_names)

#print(food_info.columns)

###可以比較出兩者的區別。

###查詢以某些字串結尾。

gram_columns =

for c in col_names:

if c.endswith("(g)"):

gram_df = food_info[gram_columns]

print(gram_df.head())

###檢視前五行資料

print(gram_df.columns)

###檢視裡面有的列。

####新加乙個列,然後將這個列加入到dataframe中

###也就是新加乙個特徵。

print(food_info.shape)

iron_g=water_energy/1000

food_info["iron_(g)"]=iron_g

print(food_info.shape)

###特殊函式的使用,例如max().mean(),min()

max_energ_kcal=food_info["energ_kcal"].max()

print(max_energ_kcal)

###使用函式進行歸一化

normal_fat=food_info["lipid_tot_(g)"]/food_info["lipid_tot_(g)"].max()

print(normal_fat)

機器學習之pandas

import pandas as pd a pd.read csv 檔案路徑 讀取檔案 a.head 顯示的條數 顯示前部分資料 a.tail 顯示的條數 顯示後部分資料 a.columns 輸出列 a.loc 序列號 輸出乙個樣本 a.columns.tolist 將列轉換成列表 c.endwit...

pandas常用函式之diff

diff函式是用來將資料進行某種移動之後與原資料進行比較得出的差異資料,舉個例子,現在有乙個dataframe型別的資料df,如下 index value1a0 b1c2 d3如果執行 df.diff 則會得到 index value1 ananb1 c1d1 怎麼得到的呢,其實是經過了兩個步驟,首...

機器學習之 Pandas 2

從網頁裡抓取資料並進行操作 import numpy as np import pandas as pd from pandas import series,dataframe import webbrowser linkur2 webbrowser.open linkur2 開啟網頁 在網頁中複製...