python常用導入函數及其他操作備忘錄
- python常用導入函數
- 解壓縮zip并讀取csv文件
- 查看缺失值
- 權重系數取絕對值后排序(查看特征權重重要度)
python常用導入函數
from
IPython
.
display
import
display
import
numpy
as
np
import
pandas
as
pd
from
pandas
import
Series
,
DataFrame
from
PIL
import
Image
import
matplotlib
.
pyplot
as
plt
%
matplotlib inline
plt
.
rcParams
[
'font.sans-serif'
]
=
[
'SimHei'
]
#用來正常顯示中文標簽
plt
.
rcParams
[
'axes.unicode_minus'
]
=
False
#用來正常顯示負號
%
config ZMQInteractiveShell
.
ast_node_interactivity
=
'all'
# nootbook使用
from
scipy
import
interp
# 線性插值
from
selenium
import
webdriver
# 我的環境變量沒有配置成功,每次都要調用路徑的Chromedriver
path
=
"D:/box/chromedriver_win32/chromedriver"
browser
=
webdriver
.
Chrome
(
executable_path
=
path
,
options
=
webdriver
.
ChromeOptions
(
)
)
browser
.
get
(
'http://www.baidu.com'
)
# 數據集拆分為訓練集和測試集
from
sklearn
.
model_selection
import
train_test_split
X_train
,
X_test
,
y_train
,
y_test
=
train_test_split
(
X
,
y
,
test_size
=
0.3
)
# 標準化數據,使每個維度的特征數據均值為0,方差為1
from
sklearn
.
preprocessing
import
StandardScaler
s
=
StandardScaler
(
)
x_train
=
s
.
fit_transform
(
X_train
)
x_test
=
s
.
transform
(
X_test
)
# 前面fit后,后面只需要transform即可
# 使用LogisticRegression建模
from
sklearn
.
linear_model
import
LogisticRegression
lr
=
LogisticRegression
(
)
lr
.
fit
(
x_train
,
y_train
)
解壓縮zip并讀取csv文件
import
pandas
as
pd
pd
.
set_option
(
'display.max_columns'
,
500
)
# 顯示最大列數,如果超出,省略號表示
import
zipfile
with
zipfile
.
ZipFile
(
'KaggleCredit2.zip'
,
'r'
)
as
z
:
f
=
z
.
open
(
'KaggleCredit2.csv'
)
data
=
pd
.
read_csv
(
f
,
index_col
=
0
)
# index_col=0表示不設置索引列,以默認數字0,1,2,3...
data
.
head
(
)
查看缺失值
data
.
isnull
(
)
# 缺失值判斷:是缺失值返回True,否則范圍False
data
.
isnull
(
)
.
sum
(
axis
=
0
)
# 缺失值計算:返回每列包含的缺失值的個數
data
.
dropna
(
)
# 缺失值刪除:直接刪除含有缺失值的行
data
.
dropna
(
inplace
=
True
)
# 刪除缺失值,并且用刪除之后的數據替換掉原數據
data
.
dropna
(
axis
=
1
)
# 缺失值刪除列:直接刪除含有缺失值的列
data
.
dropna
(
how
=
'all'
)
# 缺失值刪除行:只刪除全是缺失值的行
data
.
dropna
(
thresh
=
n
)
# 缺失值刪除判斷:保留至少有n個缺失值的行
data
.
dropna
(
subset
=
[
'C'
]
)
# 缺失值刪除列:刪除含有缺失值的特定的列
權重系數取絕對值后排序(查看特征權重重要度)
# 各個特征的權重系數
pd
.
Series
(
lr
.
coef_
[
0
]
,
index
=
X
.
columns
)
# cls.coef_[0]一維數組,否則會出錯
# 取絕對值并排序
pd
.
Series
(
np
.
abs
(
lr
.
coef_
[
0
]
)
,
index
=
X
.
columns
)
.
sort_values
(
ascending
=
False
)
# 降序排列
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
