作者:劉早起
來源:早起python,禁止二次轉載
『Pandas進階修煉120題』系列現已完結,我們對Pandas中常用的操作以習題的形式發布。從讀取數據到高級操作全部包含,希望可以通過刷題的方式來完整學習pandas中數據處理的各種方法,當然如果你是高手,也歡迎嘗試給出與答案不同的解法。
data = {"grammer":["Python","C","Java","GO",np.nan,"SQL","PHP","Python"],
"score":[1,2,np.nan,4,5,6,7,10]}
grammer score
0 Python 1.0
7 Python 10.0
result=df[df['grammer'].str.contains("Python")]
Index(['grammer', 'score'], dtype='object')
df.rename(columns={'score':'popularity'}, inplace = True)
df['grammer'].value_counts()
df['popularity'] = df['popularity'].fillna(df['popularity'].interpolate())
df.drop_duplicates(['grammer'])
df.to_excel('filename.xlsx')
df[(df['popularity'] > 3) & (df['popularity'] < 7)]
'''
方法1
'''
temp = df['popularity']
df.drop(labels=['popularity'], axis=1,inplace = True)
df.insert(0, 'popularity', temp)
df
'''
方法2
cols = df.columns[[1,0]]
df = df[cols]
df
'''
df[df['popularity'] == df['popularity'].max()]
df.drop([len(df)-1],inplace=True)
row={'grammer':'Perl','popularity':6.6}
df = df.append(row,ignore_index=True)
df.sort_values("popularity",inplace=True)
df['grammer'].map(lambda x: len(x))
df = pd.read_excel('pandas120.xlsx')
本期部分習題與該數據相關
#備註,在某些版本pandas中.ix方法可能失效,可使用.iloc,參考https://mp.weixin.qq.com/s/5xJ-VLaHCV9qX2AMNOLRtw
#為什麼不能直接使用max,min函數,因為我們的數據中是20k-35k這種字符串,所以需要先用正則表達式提取數字
import re
for i in range(len(df)):
str1 = df.ix[i,2]
k = re.findall(r"\d+\.?\d*",str1)
salary = ((int(k[0]) + int(k[1]))/2)*1000
df.ix[i,2] = salary
df
education salary
不限 19600.000000
大專 10000.000000
本科 19361.344538
碩士 20642.857143
df.groupby('education').mean()
#備註,在某些版本pandas中.ix方法可能失效,可使用.iloc,參考https://mp.weixin.qq.com/s/5xJ-VLaHCV9qX2AMNOLRtw
for i in range(len(df)):
df.ix[i,0] = df.ix[i,0].to_pydatetime().strftime("%m-%d")
df.head()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 135 entries, 0 to 134
Data columns (total 4 columns):
createTime 135 non-null object
education 135 non-null object
salary 135 non-null int64
categories 135 non-null category
dtypes: category(1), int64(1), object(2)
memory usage: 3.5+ KB
bins = [0,5000, 20000, 50000]
group_names = ['低', '中', '高']
df['categories'] = pd.cut(df['salary'], bins, labels=group_names)
df.sort_values('salary', ascending=False)
df.salary.plot(kind='hist')
df.salary.plot(kind='kde',xlim=(0,80000))
df['test'] = df['education']+df['createTime']
df["test1"] = df["salary"].map(str) + df['education']
df[['salary']].apply(lambda x: x.max() - x.min())
pd.concat([df[:1], df[-2:-1]])
createTime object
education object
salary int64
test object
test1 object
dtype: object
df.set_index("createTime")
df1 = pd.DataFrame(pd.Series(np.random.randint(1, 10, 135)))
df= pd.concat([df,df1],axis=1)
df["new"] = df["salary"] - df[0]
df['salary'].astype(np.float64)
len(df[df['salary']>10000])
本科 119
碩士 7
不限 5
大專 4
Name: education, dtype: int64
df.education.value_counts()
df['education'].nunique()
df1 = df[['salary','new']]
rowsums = df1.apply(np.sum, axis=1)
res = df.iloc[np.where(rowsums > 60000)[0][-3:], :]
data = pd.read_excel('/Users/Desktop/600000.SH.xls')
備註
請將答案中路徑替換為自己機器存儲數據的絕對路徑,本期相關習題與該數據有關
代碼 1
簡稱 2
日期 2
前收盤價(元) 2
開盤價(元) 2
最高價(元) 2
最低價(元) 2
收盤價(元) 2
成交量(股) 2
成交金額(元) 2
..
答案
data[data['日期'].isnull()]
列名:"代碼", 第[327]行位置有缺失值
列名:"簡稱", 第[327, 328]行位置有缺失值
列名:"日期", 第[327, 328]行位置有缺失值
列名:"前收盤價(元)", 第[327, 328]行位置有缺失值
列名:"開盤價(元)", 第[327, 328]行位置有缺失值
列名:"最高價(元)", 第[327, 328]行位置有缺失值
列名:"最低價(元)", 第[327, 328]行位置有缺失值
列名:"收盤價(元)", 第[327, 328]行位置有缺失值
.
答案
for columname in data.columns:
if data[columname].count() != len(data):
loc = data[columname][data[columname].isnull().values==True].index.tolist()
print('列名:"{}", 第{}行位置有缺失值'.format(columname,loc))
data.dropna(axis=0, how='any', inplace=True)
備註
axis:0-行操作(默認),1-列操作
how:any-只要有空值就刪除(默認),all-全部為空值才刪除
inplace:False-返回新的數據集(默認),True-在原數據集上操作
答案
data[['收盤價(元)','開盤價(元)']].plot()
備註
中文顯示請自己設置,我的字體亂了
答案
data['漲跌幅(%)'].hist(bins = 30)
temp = pd.DataFrame(columns = data.columns.to_list())
for i in range(len(data)):
if type(data.iloc[i,13]) != float:
temp = temp.append(data.loc[i])
temp
data[data['換手率(%)'].isin(['--'])]
備註
通過上一題我們發現換手率的異常值只有--
data = data.reset_index()
備註
有時我們修改數據會導致索引混亂
k =[]
for i in range(len(data)):
if type(data.iloc[i,13]) != float:
k.append(i)
data.drop(labels=k,inplace=True)
data['換手率(%)'].plot(kind='kde')
data['收盤價(元)'].pct_change()
題目:以5個數據作為一個數據滑動窗口,在這個5個數據上取均值(收盤價)
data['收盤價(元)'].rolling(5).mean()
題目:以5個數據作為一個數據滑動窗口,計算這五個數據總和(收盤價)
data['收盤價(元)'].rolling(5).sum()
題目:將收盤價5日均線、20日均線與原始數據繪製在同一個圖上
data['收盤價(元)'].plot()
data['收盤價(元)'].rolling(5).mean().plot()
data['收盤價(元)'].rolling(20).mean().plot()
題目:按周為採樣規則,取一周收盤價最大值
data['收盤價(元)'].resample('W').max()
題目:繪製重採樣數據與原始數據
data['收盤價(元)'].plot()
data['收盤價(元)'].resample('7D').max().plot()
data['開盤價(元)'].expanding(min_periods=1).mean()
答案
data[' expanding Open mean']=data['開盤價(元)'].expanding(min_periods=1).mean()
data[['開盤價(元)', 'expanding Open mean']].plot(figsize=(16, 6))
data['former 30 days rolling Close mean']=data['收盤價(元)'].rolling(20).mean()
data['upper bound']=data['former 30 days rolling Close mean']+2*data['收盤價(元)'].rolling(20).std()#在這裡我們取20天內的標準差
data['lower bound']=data['former 30 days rolling Close mean']-2*data['收盤價(元)'].rolling(20).std()
data[['收盤價(元)', 'former 30 days rolling Close mean','upper bound','lower bound' ]].plot(figsize=(16, 6))
import pandas as pd
import numpy as np
print(np.__version__)
print(pd.__version__)
tem = np.random.randint(1,100,20)
df1 = pd.DataFrame(tem)
tem = np.arange(0,100,5)
df2 = pd.DataFrame(tem)
tem = np.random.normal(0, 1, 20)
df3 = pd.DataFrame(tem)
df = pd.concat([df1,df2,df3],axis=0,ignore_index=True)
0 1 2
0 95 0 0.022492
1 22 5 -1.209494
2 3 10 0.876127
3 21 15 -0.162149
4 51 20 -0.815424
5 30 25 -0.303792
df = pd.concat([df1,df2,df3],axis=1,ignore_index=True)
df
print(np.percentile(df, q=[0, 25, 50, 75, 100]))
df.columns = ['col1','col2','col3']
df['col1'][~df['col1'].isin(df['col2'])]
temp = df['col1'].append(df['col2'])
temp.value_counts().index[:3]
np.argwhere(df['col1'] % 5==0)
df['col1'].diff().tolist()
df['col1'].take([1,10,15])
tem = np.diff(np.sign(np.diff(df['col1'])))
np.where(tem == -2)[0] + 1
df[['col1','col2','col3']].mean(axis=1)
np.convolve(df['col2'], np.ones(3)/3, mode='valid')
df.sort_values("col3",inplace=True)
df.col1[df['col1'] > 50]= '高'
np.linalg.norm(df['col1']-df['col2'])
df = pd.read_csv('數據1.csv',encoding='gbk', usecols=['positionName', 'salary'],nrows = 10)
答案
df = pd.read_csv('數據2.csv',converters={'薪資水平': lambda x: '高' if float(x) > 10000 else '低'} )
期望結果
答案
df.iloc[::20, :][['薪資水平']]
df = pd.DataFrame(np.random.random(10)**10, columns=['data'])
期望結果
答案
df.style.format({'data': '{0:.2%}'.format})
df['data'].argsort()[::-1][7]
df1= pd.DataFrame({'key1': ['K0', 'K0', 'K1', 'K2'],
'key2': ['K0', 'K1', 'K0', 'K1'],
'A': ['A0', 'A1', 'A2', 'A3'],
'B': ['B0', 'B1', 'B2', 'B3']})
df2= pd.DataFrame({'key1': ['K0', 'K1', 'K1', 'K2'],
'key2': ['K0', 'K0', 'K0', 'K0'],
'C': ['C0', 'C1', 'C2', 'C3'],
'D': ['D0', 'D1', 'D2', 'D3']})
pd.merge(df1, df2, on=['key1', 'key2'])
備註
只保存df1的數據
答案
pd.merge(df1, df2, how='left', on=['key1', 'key2'])
df = pd.read_csv('數據1.csv',encoding='gbk')
pd.set_option("display.max.columns", None)
df
np.where(df.secondType == df.thirdType)
np.argwhere(df['salary'] > df['salary'].mean())[2]
df[['salary']].apply(np.sqrt)
df['split'] = df['linestaion'].str.split('_')
df[df['industryField'].str.startswith('數據')]
pd.pivot_table(df,values=["salary","score"],index="positionId")
df[["salary","score"]].agg([np.sum,np.mean,np.min])
df.agg({"salary":np.sum,"score":np.mean})
df[['district','salary']].groupby(by='district').mean().sort_values('salary',ascending=False).head(1)
以上就是Pandas進階修煉120題全部內容,如果能堅持走到這裡的讀者,我想你已經掌握了處理數據的常用操作,並且在之後的數據分析中碰到相關問題,希望武裝了Pandas的你能夠從容的解決!
另外我已將習題與源碼整理成電子版,後臺回復 120 即可下載
後臺回復「進群」,加入讀者交流群~
昨日最多贊留言「HeoiJinChan」+26積分;
純眼熟留言「瓜」+50積分
【凹凸數據】本次聯合【機械工業出版社】為大家送上1本《Hive性能調優實戰》,限時500積分即可兌換,先到先得