本章的10道題仍然是基于前章的文件,主要學習了有設置索引、合并兩個DataFrame對象、更改數(shù)據(jù)類型,不同列之間的運算,統(tǒng)計一列不同值得個數(shù)以及不同值分別出現(xiàn)得次數(shù),還有如何靈活的運用布爾值運算。
前期準備
## 前期準備
本章的十道題與前面的試題相連接,數(shù)據(jù)集用的同一個數(shù)據(jù)集一些操作也是基于上一個練習的
本次導包多導入了一個繪圖的包,在這里我們只是簡單的應用,后面會有詳細的講解用法
```python
import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
數(shù)據(jù)集沒有的可以私信我,也可以直接去我的資源里面找
df = pd.read_excel('data1.xlsx')
def fun(x):
a,b = x.split('-')
a = int(a.strip('k'))*1000
b = int(b.strip('k'))*1000
return int((a+b)/2)
df['salary'] = df['salary'].apply(fun)
1. 將create Time列設置為索引
set_index() 將DataFrame的某一列快速設置成索引(index)默認會刪除原來的列同樣也可以是使用drop=False
不刪除原來的列
df.set_index('createTime')
2. 生成一個和df長度相同的隨機數(shù)DataFrame
隨機數(shù)的范圍1-1000
隨機生成
df1=pd.DataFrame(pd.Series(np.random.randint(1,1000,df.shape[0])))
3. 將上一題生成的DataFrame與df合并
其實這個題本質(zhì)上就是合并兩個DataFrame對象
- 使用merge
這個merge多用于內(nèi)連接和外連接
pd.merge(df,df1)
- 使用concat
df = pd.concat([df,df1],axis=1)
df
- 使用join
df.join(df1)
兩個合并之后的情況
4. 生成的新的一列new值為salary列減去之前生成的隨機數(shù)列
df['new'] = df['salary'].astype('int') - df['rom']
df
5. 檢查數(shù)據(jù)中是否含有空值
isnull()對所有的元素判斷是否是空值
any() 當序列中有一個True
值時返回True
否則返回False
all() 當序列中所有的值為True
值時返回True
否則返回False
df.isnull().values.any()
6. 將salary類型轉(zhuǎn)換成浮點數(shù)
類型轉(zhuǎn)換
這種方式并不會修改原數(shù)據(jù),會返回一個修改后的新對象
df['salary'].astype('float') # 方式1
df['salary'].astype(np.float64) # 方式2
7. 計算salary 大于10000的次數(shù)
其實這個里面用了一個布爾值計算的等價計算
True代表1 False代表0
sum(df['salary']>10000)
8. 查看education共有幾種學歷
統(tǒng)計一列中的不同值得個數(shù)
# 方式1
df.education.nunique()
# 方式2
df['education'].nunique()
9. 查看每種學歷出現(xiàn)的次數(shù)
統(tǒng)計每一種值出現(xiàn)得次數(shù)
df['education'].value_counts() # 方式1
df.education.value_counts() # 方式2
10. 提取salary與new的和大于60000的最后3行
推薦使用前兩種文章來源:http://www.zghlxwxcb.cn/news/detail-407804.html
# 提取salary與new的和大于60000的最后3行
# 方式1
df[df['salary']+df['new']>60000].tail(3)
# 方式2
df[df['salary']+df['new']>60000][-3:]
# 方式3
df2 = df[['salary','new']]
rowsums = df2.apply(np.sum,axis=1)
res = df.iloc[np.where(rowsums>60000)[0][-3:],:]
res
文章來源地址http://www.zghlxwxcb.cn/news/detail-407804.html
到了這里,關(guān)于數(shù)據(jù)分析 | Pandas 200道練習題,每日10道題,學完必成大神(5)的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!