這篇主要比較R語言的data.talbe和python的pandas操作數(shù)據(jù)框的形式, 學(xué)習(xí)兩者的異同點(diǎn), 加深理解兩者的使用方法。
這里使用R語言的data.table
t包和python的pandas
進(jìn)行對(duì)比.
主要分為三部分:
新建數(shù)據(jù)庫
行列選擇
行列篩選
data.table介紹:
library(data.table)
set.seed(123)
DT <- data.table(V1=c(1,2),V2=c("A","B","C"),V3=round(rnorm(4),4), V4=1:12)
選擇單行
# 行選擇
DT[2]
DT[2,] # 同上
選擇多行
DT[3:5]
DT[3:5,]
選擇列
DT[,2]
DT[,.(V2)] # 同上
DT[,list(V2)]
選擇V2等于A的列
DT[V2=="A"]
DT[V2=="A",]
如果選擇V2等于A或者等于B的列
DT[V2 == "A"|V2=="B"]
%in%
進(jìn)行多條件選擇DT[V2 %in% c("A","B")]
新建一列V5
DT[,V5:=V3*V4]
DT
fwrite(DT,"DT.csv")
讀取數(shù)據(jù)
import pandas as pd
df = pd.read_csv("DT.csv")
df
df[0]
報(bào)錯(cuò), 要用df[0:1]df[0:1] # 如果直接使用, 需要給出區(qū)間
# loc 根據(jù)行名
df.loc[1] # 注意, python從0開始
也可以根據(jù)iloc進(jìn)行提取
# iloc 根據(jù)行號(hào)
df.iloc[1]
注意, iloc是根據(jù)行號(hào), loc是根據(jù)行名
選擇多行
df[3:6] # 3包括, 6不包括
同上:
df.loc[3:5]
df["V2"]
也可以使用列數(shù), 使用iloc
df.iloc[:,1:2]
如果使用多個(gè)列名, 要用[]
df[["V1","V2"]] # 用兩個(gè)[][]
df.iloc[:,0:2]
df[df['V2']=="A"]
或者:
df[df['V2']=="A"]
多條件篩選
# 麻煩style: (df['V2']=='A')|(df['V2']=='B')
df[(df['V2']=='A')|(df['V2']=='B')]
也可以使用isin進(jìn)行操作:
# 使用.V2.isin()進(jìn)行多條件篩選
df[df.V2.isin(["A","B"])]
# 使用[].isin也可以
df[df['V2'].isin(["A","B"])]
創(chuàng)建新列V5
df.V5 = df.V3*df.V4
df
如果是R的思維:
write.csv(object, "file.csv")
但是pandas的風(fēng)格是
object.to_csv("file.csv")
正確有效的代碼:
df.to_csv("df.csv",index=0) # 對(duì)象.to_csv, 不是pd.write(df,"df.csv")!!!
聯(lián)系客服