前言
記錄下寫程序過程中用到的覺得實用的pandas操作, 不斷更新下,方便自己查找
多重條件篩選
df[(條件1) & (條件2)]
import pandas as pd
import numpy as np
A = np.random.rand(3, 3)
B = pd.DataFrame(A)
# 多重條件篩選
B[(B[0]>0.1) & (B[1]<0.8)]
用exec在循環裏更改變量名稱
想在循環裏, 賦值不同名稱的變量時:
for i in range(5):
exec("a" + str(i) + "=i")
和 eval的區別:
- exec 運行一段程序,返回None
- eval 運行一個表達式, 返回表達式結果。
>>> a = 5
>>> eval('37 + a') # it is an expression
42
>>> exec('37 + a') # it is an expression statement; value is ignored (None is returned)
>>> exec('a = 47') # modify a global variable as a side effect
>>> a
47
>>> eval('a = 47') # you cannot evaluate a statement
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1
a = 47
^
SyntaxError: invalid syntax
按字符串包含字符篩選
.str.contains()
>>> B[3] = ['中國', '美國', '歐洲']
>>> B
0 1 2 3
0 0.179662 0.856873 0.291942 中國
1 0.008990 0.473773 0.659489 美國
2 0.525482 0.710721 0.241518 歐洲
>>> B[B[3].str.contains('國')]
>>> 0 1 2 3
0 0.179662 0.856873 0.291942 中國
1 0.008990 0.473773 0.659489 美國
.isin()
>>> B[B[3].isin(['中國', '美國', '英國'])]
>>> 0 1 2 3
0 0.179662 0.856873 0.291942 中國
1 0.008990 0.473773 0.659489 美國
按列獲取數據
# 通過列名獲取
tmp = df['列名'] # tmp 就是獲取的列
# 列名太長, 不打,用索引獲取第三列
tmp = df[df.columns[3]]
# 另一種方法,也可以獲取多列
tmp = df.iloc[:, 3]
tmp = df.iloc[:m 3:5]