pandas 變數列的基本操作

2021-09-28 12:26:32 字數 2762 閱讀 7127

import pandas as pd

df1 = pd.read_csv(

'123.csv'

,encoding =

'utf-8'

)

print

(df1)

# directly show dataframe 直接檢視

print

(df1.info)

#dataframe's basic information 資訊描述

print

(df1.head(10)

)#glance over top 10 records 看前十行

print

(df1.tail(10)

)#glance over last 10 records 看後十行

print

(df1.columns)

#show columns' name 列印所有列名稱

df1.columns =

['storename'

,'star'

,'consumption'

,'address'

,'phone'

]print

(df1.columns)

df2 = df1.rename(

columns =

,#note wrong name will be ignored 錯誤或者沒有的列名將忽略不報錯

inplace =

false

#if or not directly replace dataframe

)print

(df2)

df[

'var'

] single columns outcome is series,use list can change it to df

df[[

'var1'

,'var2'

]] multi-columns' usage,var not exit

del df[

'columns-name'

]# directly delet df columns

print

(df2[

['stars'

,'phone']]

)#delet columns

df.drop(

index/columns = row/columns' label ready to delet ,more than one use list

inplace =

false

)#刪除行和列

print

(df2.drop(columns =

['stars'

,'phone'])

)print

(df2.drop(index =[0

,1])

)

pandas' data type

:#所支援的型別

float

,int

,string,

bool

,datetime64[ns]

,datetime64[ns,tz]

,timedelta[ns]

category,

object

print

(df2.dtypes)

df2.astype(

dtype:assign new type you want (

int/

float

/bool

/str

) copy:same to inplace;

true

is default

erroes =

'raise':if

ornot

raise errors [ignore/

raise])

'''print

(df2.astype(

'str'

).dtypes)

#所有列轉換為str

print

(df2.stars.astype(

'float'))

#列stars轉換為float

print

(df2.stars.astype(

'float'

).dtypes)

print

(df2[

['stars'

,'phone']]

.astype(

'str'

).dtypes)列stars和phone轉換為str

print

(df2[

['stars'

,'phone']]

.astype(

'str').

(pd.to_numeric,errors =

'ignore'

).dtypes)

df3 = pd.dataframe(

)df = df3.iloc[1:

]print

(df )

print

(df.dtypes)

print

(df3.infer_objects(

).dtypes)

#auto-convert types 自動識別型別並轉換,經測試並不好用

pandas 刪除列和行的基本操作

用法 dataframe.drop labels none,axis 0,index none,columns none,inplace false labels 就是要刪除的行列的名字,用列表給定 axis 預設為0,指刪除行,因此刪除columns時要指定axis 1 index 直接指定要刪除...

pandas的基本操作

資料讀寫 讀入mysql資料庫資料 匯入第三方模組 import pymysql 連線mysql資料庫 conn pymysql.connect host localhost user root password test database test port 3306 charset utf8 讀...

pandas的基本操作

準備工作 我們需要裝好pandas庫,然後引入它,一般簡寫為pd import pandas as pd1 生成乙個 方法一 pd.dataframe 三個引數,第乙個為填入的值,第二個index為 的行標,第三個columns為 的列標。第二三個引數如果不填則預設從0開始一直排下去。方法一直接使用...