继续前面的练习,之前的文章参考:
- pandas实例-了解你的数据-Chipotle
- pandas实例-筛选与排序-Chipotle
- pandas实例-数据可视化-Chipotle
- pandas实例-了解你的数据-Occupation
- pandas实例-筛选与过滤-Euro 12
这一篇,依然是练习筛选和过滤,原文参考:https://github.com/guipsamora/pandas_exercises
这一回,没有数据集,数据只作者自己造的,好的,我们继续来学习吧
raw_data = {'regiment': ['Nighthawks', 'Nighthawks', 'Nighthawks', 'Nighthawks', 'Dragoons', 'Dragoons', 'Dragoons', 'Dragoons', 'Scouts', 'Scouts', 'Scouts', 'Scouts'],
'company': ['1st', '1st', '2nd', '2nd', '1st', '1st', '2nd', '2nd','1st', '1st', '2nd', '2nd'],
'deaths': [523, 52, 25, 616, 43, 234, 523, 62, 62, 73, 37, 35],
'battles': [5, 42, 2, 2, 4, 7, 8, 3, 4, 7, 8, 9],
'size': [1045, 957, 1099, 1400, 1592, 1006, 987, 849, 973, 1005, 1099, 1523],
'veterans': [1, 5, 62, 26, 73, 37, 949, 48, 48, 435, 63, 345],
'readiness': [1, 2, 3, 3, 2, 1, 2, 3, 2, 1, 2, 3],
'armored': [1, 0, 1, 1, 0, 1, 0, 1, 0, 0, 1, 1],
'deserters': [4, 24, 31, 2, 3, 4, 24, 31, 2, 3, 2, 3],
'origin': ['Arizona', 'California', 'Texas', 'Florida', 'Maine', 'Iowa', 'Alaska', 'Washington', 'Oregon', 'Wyoming', 'Louisana', 'Georgia']}
df = pd.DataFrame(data=raw_data)
df.head()
1. 将origin
设置为index
参考之前的一篇:Pandas实例-把某一列指定为index
df.set_index('origin' , inplace=True)
df.head()
2. 只显示“veterans”一列数据
df.loc[: , 'veterans']
df.loc[: , ['veterans']]
df[['veterans']]
3. 显示 'veterans' and 'deaths' 两列数据
df[['veterans','deaths']]
df.loc[: , ['veterans','deaths']]
这两道题,都是针对column筛选,使用loc函数,或者标签的形式
4. 显示所有的列名
df.columns
5. Select the 'deaths', 'size' and 'deserters' columns from Maine and Alaska
也是筛选,针对index和column筛选
df.loc[['Maine','Alaska'] , ['deaths','size','deserters']]
6. Select the rows 3 to 7 and the columns 3 to 6
上面是根据label来筛选,这一题是根据下标来筛选,使用另一个函数,iloc
df.iloc[2:7 , 2:6]
这里要注意下,下标是从0开始
df.iloc[2:7 , 2:6]
7. 筛选死亡人数大于50的记录
df[df['deaths']>50].sort_values(by='deaths',ascending=False)
8. 筛选死亡人数大于500或者小于50的记录
这里要注意下,多个条件怎么写,得加上括号
df[(df['deaths']>500) | (df['deaths']<50)]
还发现一种写法,感觉更简洁,更像SQL
df.query('deaths>500 | deaths<50')
我得牢记这个query函数,感觉很好用,我要去写一篇专门的query使用,
9. Select all the regiments not named "Dragoons"
df.query('regiment != "Dragoons"')
10. Select the rows called Texas and Arizona
df.loc[['Texas','Arizona'] ]
正常来看,这样写就行了,但是我们刚刚知道了query
,看看用query
怎么写
df.query('index in ("Texas","Arizona")')
有意思