DataFrame包含索引和數(shù)據(jù)
- 基本操作
df.dtypes 顯示每列的數(shù)據(jù)類型
df.head()
df.tail(3)
df.index
df.columns
df.columns=['name','url','band'] 重命名列名
df.values
df.describe()
df.T 對數(shù)據(jù)進(jìn)行轉(zhuǎn)置
df.sort(columns='likes')
2、選取數(shù)據(jù)
df['A'] A是列名
df[1:5] 索引1~4行的數(shù)據(jù)
df.loc[0:3,['nickname','likes']] 按索引,取nickname,likes數(shù)據(jù)
(包括索引3的數(shù)據(jù)剑辫,共4條)
df.loc[:,['articles','likes','nickname']] 取指定3列的全部數(shù)據(jù)
df.at[0,'url'] 取第一行數(shù)據(jù)的url值
df[df.articles>50] 選擇articles大于50的記錄
3、數(shù)據(jù)去重
newdf = df.drop_duplicates() 返回一個(gè)新的dataframe
data.drop_duplicates(['k2']) 按列去重
4稚照、缺失數(shù)據(jù)處理
1)數(shù)據(jù)補(bǔ)齊,用一定的值去填充
newdf = df.dropna()
2)刪除對應(yīng)缺失行
3)不處理
5、空格值處理
strip() 清理值前后的空格
newname = df['name'].str.strip()
6果录、字段抽取
slice(start,stop)
df['tel']=df['tel'].astype(str)
bands = df['tel'].str.slice(0,3)
7上枕、字段拆分
split(sep,n,expand=False)
sep 用于分割的字符串
n 分割為多少列
expand True, 返回DataFrame; False, 返回Series
newdf = df['name'].str.split(' ',1,True)
8、字段合并
DataFrame不同列合并操作弱恒,列先需要轉(zhuǎn)為字符型
x = x1+x2+...
9辨萍、數(shù)據(jù)抽取 (數(shù)據(jù)過濾)
1)比較運(yùn)算
df[df.comment>200]
2)范圍運(yùn)算
df[df.articles.between(50,100)]
3)空值匹配
df[pandas.isnull(df.title)]
4)字符匹配
df[df.title.str.contains('Apple',na=False)]
na=False表示空值不匹配
5)邏輯運(yùn)算
與(&), 或(|), 取反(not)
df[(df.comments>=500) & (df.comments<=1000)]
10、隨機(jī)抽樣
numpy.random.randint(start,end,number)
start 范圍的開始值
end 范圍的結(jié)束值
number 抽樣個(gè)數(shù)
11返弹、記錄合并
將兩個(gè)DataFrame合并
df = pandas.contact([df1,df2,df3])
12锈玉、字段匹配
相當(dāng)SQL多表聯(lián)合查詢(內(nèi)連接)
newdf = pandas.merge(
item,
price,
left_on='id',
right_on='id'
)
兩個(gè)dataframe, item和price ,由id進(jìn)行連接
13义起、計(jì)算列
對列進(jìn)行簡單計(jì)算
result = df.price* df.num
df['sum']=result
14拉背、日期轉(zhuǎn)換
from pandas import to_datetime
df_dt=to_datetime(df.regtime, format='%Y-%m-%d')
15、日期格式化
將日期型的數(shù)據(jù)默终,按照給定的格式椅棺,轉(zhuǎn)為字符型的數(shù)據(jù)
apply(lambda x: 處理邏輯)
datetime.strftime(x,format)
df_dt_str=df_dt.apply(lambda x: datetime.strftime(x,'%Y-%m-%d'))