DAY 7
0
AI & Data

## list

``````# 篩選list-使用列表推導式
list1 = [1,2,3,4,5,6]
list2 = [x for x in list1 if x % 2 == 1] # 篩選奇數元素
list2
# [1, 3, 5]
``````
``````# 篩選list-使用filter()
list1 = [1,2,3,4,5,6]
list2 = list(filter(lambda x : x % 2 == 1, list1)) # 記得要再放進去list()裡面才會得到list
list2
# [1, 3, 5]
``````

## dict

``````# 篩選dict
dict1 = {"a":1, "b":2, "c":3}

# 按key篩選
dict2 = {k:v for k,v in dict1.items() if k in ["a","c"]} # 篩選key是a或c的
dict2
# {'a': 1, 'c': 3}

# 按value篩選
dict3 = {k:v for k,v in dict1.items() if v%2 == 1} # 篩選value是奇數的
dict3
# {'a': 1, 'c': 3}
``````

## DataFrame

``````# 篩選DataFrame
import pandas as pd
df = pd.DataFrame({"a":[1,2,3], "b":[4,5,6], "c":[7,8,9], "d":[True, True,False]})
df
``````

### 根據列表名稱篩選column

``````# 篩選a,c col
df[["a","c"]]
``````

### 根據布林值篩選row

``````# 根據布林col來篩選
df[df["d"]] # 只會取出d-col中為True的結果
``````

### 用`isin`篩選特定條件

``````mask = df.isin({"a":[1,3], "b":[4,5], "c":[7,8,9], "d":[True,False]})
``````

### 依照DataFrame內容文字篩選

``````df["col_name"].str.contains("some text")
``````

### 1 則留言

0
WeiYuan
iT邦新手 4 級 ‧ 2021-09-22 23:20:27

owo iT邦新手 5 級 ‧ 2021-09-23 00:34:26 檢舉

https://jikipedia.com/definition/1069903267?action=%5Bobject%20PointerEvent%5D

WeiYuan iT邦新手 4 級 ‧ 2021-09-23 00:59:11 檢舉

... 我果然老了

owo iT邦新手 5 級 ‧ 2021-09-23 22:59:45 檢舉