=====================
Булевская маскировка
=====================
(.env) boris@boris-All-Series:~/MASK$ cat boleanPandas1.py
import pandas as pd
df = pd.DataFrame({"A":[3,4,5], "B":[6,7,8]}, index=["a","b","c"])
print(df)
print('\n')
mask = [False, True, True]
print(df[mask])
(.env) boris@boris-All-Series:~/MASK$ python3 boleanPandas1.py
A B
a 3 6
b 4 7
c 5 8
A B
b 4 7
c 5 8
(.env) boris@boris-All-Series:~/MASK$ cat boleanPandas2.py
import pandas as pd
df = pd.DataFrame({"A":[3,4,5], "B":[6,7,8]}, index=["a","b","c"])
print(df)
print('\n')
mask = [True,False,True]
print(df.loc[mask])
(.env) boris@boris-All-Series:~/MASK$ python3 boleanPandas2.py
A B
a 3 6
b 4 7
c 5 8
A B
a 3 6
c 5 8
=======
Фильтры
=======
Можно комбинировать логические фильтры, подобные операторам if. У нас есть два примера ниже.
Первый показывает, как мы можем использовать | оператор для создания или сравнения.
(.env) boris@boris-All-Series:~/MASK$ cat maskPandas1.py
import pandas as pd
df = pd.DataFrame([
{
"person": "James",
"sales": 1000,
"lastName": "Taylor",
},
{
"person": "Luna",
"sales": 2000,
"lastName": "Mound"
},
{
"person": "Clara",
"sales": 3000,
"lastName": "Brown"
},
])
print(df)
print('\n')
filtered = df[(df['sales'] <= 1000) | (df['sales'] >= 3000)]
print(filtered)
(.env) boris@boris-All-Series:~/MASK$ python3 maskPandas1.py
person sales lastName
0 James 1000 Taylor
1 Luna 2000 Mound
2 Clara 3000 Brown
person sales lastName
0 James 1000 Taylor
2 Clara 3000 Brown
(.env) boris@boris-All-Series:~/MASK$
Во втором примере показано, как использовать оператор & для создания сравнения и.
(.env) boris@boris-All-Series:~/MASK$ cat maskPandas2.py
import pandas as pd
df = pd.DataFrame([
{
"person": "James",
"sales": 1000,
"lastName": "Taylor",
},
{
"person": "Luna",
"sales": 2000,
"lastName": "Mound"
},
{
"person": "Clara",
"sales": 3000,
"lastName": "Brown"
},
])
print(df)
print('\n')
filtered = df[(df['sales'] > 1000) & (df['sales'] < 3000)]
print(filtered)
(.env) boris@boris-All-Series:~/MASK$ python3 maskPandas2.py
person sales lastName
0 James 1000 Taylor
1 Luna 2000 Mound
2 Clara 3000 Brown
person sales lastName
1 Luna 2000 Mound
No comments:
Post a Comment