whystea2

assign
df.assign(
col3=df["col2"].str.upper(),
col4=df["col1"] * 3 / 4 + 25,
col5=lambda x: x["col1"] / 2 + 10,
col6=lambda x: x["col5"] * 5, # 在col6计算中直接使用col5

col7=lambda x: x.col2.str.upper(),         
col8=lambda x: x.col7.str.title()  # col8中使用col7

)
与apply的区别是,会返回一个新的dataframe,原本的dataframe不会变


loc
concat

['']
concat
删 - drop

label axis=0
index

label axis=1
colunms
dropna
import pandas as pd

axis=0或axis='index’删除含有缺失值的行
axis=1或axis='columns’删除含有缺失值的列
thresh表示保留至少有threash个的

创建包含缺失值的数据框

data = {'A': [1, 2, None, 4],
'B': [None, 6, 7, 8],
'C': [9, 10, 11, 12]}
df = pd.DataFrame(data)

删除包含缺失值的行

cleaned_df = df.dropna()

删除包含缺失值的列

cleaned_df = df.dropna(axis=1)

只删除整行或整列都是缺失值的行或列

cleaned_df = df.dropna(how='all')

至少需要2个非缺失值才保留行或列

cleaned_df = df.dropna(thresh=2)

只在特定列中检查缺失值

cleaned_df = df.dropna(subset=['A', 'C'])

在原始数据上进行就地修改

df.dropna(inplace=True)

roc曲线、auc值
fpr,tpr,_=roc_curve(y_test,y_score)
auc=auc(fpr,tpr)
plt.plot(fpr,tpr,label='ROC curve (area=%.2f)'%auc)
plt.plot([0,1],[0,1],linestyle='--')
subplot
-不同图之间的间隔
pyplot.subplots_adjust()
param:
left,right,bottom,top 0-1 之间是指在整张图的百分比
wspace 子图之间横向间隔
hspace 子图之间纵向间隔
-标题
pyplot.title
param:
label:显示内容
loc:(center|left|right)显示位置
y:1.0是在top
pad:距离top的间隔

颜色
字体
标记
https://www.bilibili.com/video/BV18f4y1u7tK/?vd_source=ec7740b3018d25c8c0c9e384eb9c44b7
plt.text(x,y,text)
plt.annotate(text,xy,xytext,arrowprops=dict(arrowstyle='-->'))
线型
-横纵坐标标记
pyplot.xticks()
param:
ticks:表示显示标题的位置
labels:位置上显示的内容
rotation:旋转的角度
plt.xticks([1,2,3,4,5],['yi','er','san','si','wu'])
-横纵坐标内容
pyplot.xlabel()
param:
xlabel
labelpad
loc
-横纵坐标显示范围
pyplot.xlim()
1.返回现在的范围
2.left=1,right=5 设置显示的坐标轴范围
图标
https://zhuanlan.zhihu.com/p/651600668
标上y值
图类型
suplots、ax

using the variable ax for single a Axes

fig, ax = plt.subplots()

using the variable axs for multiple Axes

fig, axs = plt.subplots(2, 2)

using tuple unpacking for multiple Axes

fig, (ax1, ax2) = plt.subplots(1, 2)
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2)
中文显示
plt.rcParams['font.sans-serif']=['SimHei']
plt.rcParams['axes.unicode_minus']=False
apply、map
https://zhuanlan.zhihu.com/p/584036056

map常用于字典映射
如果只映射部分,会将未映射的变为None
apply常用于函数,可以额外添加参数,可用于列函数映射对应,axis可选0、1 0-列 1-行

参数

df['Python优秀'] = df['Python成绩'].apply(get_python_Goodornot, args=(80,))

映射

df['Python成绩'].apply({'A':lambda x:x+1, 'B':lambda x:x+2})

每个人的最大成绩 1-行

apply 可以用于多维

df[['Python成绩', '英语成绩']].apply(np.max, axis=1)
df[['Python成绩', '英语成绩']].apply(lambda x:x['Python成绩']-x['英语成绩'], axis=1)

每科的最大成绩 0-列

df[['Python成绩', '语文成绩', '数学成绩', '英语成绩']].apply(np.max, axis=0)
applymap用于整个的每一个
quantile
df.quantile(0.2)
interplot
df.interpolate()
param:
method:linear、index、time
fillna
df.fillna()
param:
value:
method:ffill、bfill 向前、向后
limit:连续na时,最多填补的个数

df = pd.DataFrame([[np.nan, 2, np.nan, 0],
[3, 4, np.nan, 1],
[np.nan, np.nan, np.nan, 5],
[np.nan, 3, np.nan, 4]],
columns=list("ABCD"))
df
A B C D
0 NaN 2.0 NaN 0
1 3.0 4.0 NaN 1
2 NaN NaN NaN 5
3 NaN 3.0 NaN 4

df.fillna(method="ffill")
A B C D
0 NaN 2.0 NaN 0
1 3.0 4.0 NaN 1
2 3.0 4.0 NaN 5
3 3.0 3.0 NaN 4

values = {"A": 0, "B": 1, "C": 2, "D": 3}
df.fillna(value=values)
A B C D
0 0.0 2.0 2.0 0
1 3.0 4.0 2.0 1
2 0.0 1.0 2.0 5
3 0.0 3.0 2.0 4

df.fillna(value=values, limit=1)
A B C D
0 0.0 2.0 2.0 0
1 3.0 4.0 NaN 1
2 NaN 1.0 NaN 5
3 NaN 3.0 NaN 4

//照着另一个df填充

df2 = pd.DataFrame(np.zeros((4, 4)), columns=list("ABCE"))
df.fillna(df2)
A B C D
0 0.0 2.0 0.0 0
1 3.0 4.0 0.0 1
2 0.0 0.0 0.0 5
3 0.0 3.0 0.0 4
rank - https://zhuanlan.zhihu.com/p/635129284
param:
ascending:True,False
method:
average:相同排名下,取平均值进行排名。比如李四、王五为第二、第三名,孙7为第四名,那么李四、王五取值为2.5,孙7取值为4。
min:相同排名下,取较小的排名。比如李四、王五为第二、第三名,孙7为第四名,那么李四、王五取值为2,孙7取值为4。
max:相同排名下,取较大的排名。比如李四、王五为第二、第三名,孙7为第四名,那么李四、王五取值为3,孙7取值为4。
first:相同排名下,按原来的顺序进行排序。比如李四、王五为第二、第三名,孙7为第四名,那么李四取值为2,王五取值为3,孙7取值为4。
dense:类似min,不过后续值排名在此排名基础上加一。比如李四、王五为第二、第三名,孙7为第四名,那么李四、王五取值为2,孙7取值为3。
pct:百分比显示

df['班级Python成绩排名'] = df.groupby('班级')['Python成绩'].rank(method='min', ascending=False)
sample
param:
frac:百分比
n:抽样多少个数
replace: frac>1 or n>数 时 replace 只能为true
groupby
-https://zhuanlan.zhihu.com/p/607906239?utm_id=0&wd=&eqid=cfdd347c00082b9e00000004646b4463

param:
by
group_keys:true 使用by列作为索引 false 使用原索引

多个聚合

df.groupby(by='区域')['利润'].agg(['max','min','mean'])

多层

df.groupby(by='类别').agg({'利润':['max','min','mean'],'销售额':['max','min','mean']}

自定义新列名

df.groupby(by='类别').agg(总销售额=('销售额','sum'),总利润=('利润','sum'),平均利润=('利润',profit_mean))

分组时使用apply

df.groupby(by='类别').agg(总销售额=('销售额','sum'),总利润=('利润','sum'),平均利润=('利润',profit_mean))

聚合时使用apply

df.groupby(by='区域')['产品名称'].apply(lambda x : x.str.contains('红色').sum())

sort_values排序

df.groupby(by=['区域',df.订单日期.apply(lambda x : x.year)],group_keys=False).agg({'销售额':'sum'}).sort_values(by=['销售额'],ascending=False).reset_index().groupby('区域').first()

修改索引名 多个索引

df_group = df.groupby(by=['区域',df.订单日期.apply(lambda x : x.year)],group_keys=False).agg({'销售额':'sum'})

df_group.index.names = ['区域','年份']

df_group = df_group.rename_axis(['区域','年份'])

transform

df_group['avg_profit'] = df_group.groupby('区域')['平均利润'].transform('mean')

filter

f.groupby(by='子类别').filter(lambda x:x.数量.sum() > 1000)
insert
df.insert(loc,column,value)
-插入新列

df = pd.DataFrame({'col1': [1, 2], 'col2': [3, 4]})
df
col1 col2
0 1 3
1 2 4
df.insert(1, "newcol", [99, 99])
df
col1 newcol col2
0 1 99 3
1 2 99 4
df.insert(0, "col1", [100, 100], allow_duplicates=True)
df
col1 col1 newcol col2
0 100 1 99 3
1 100 2 99 4
pop
df.pop(item)
删除并返回列名为item的列
sort_index -https://zhuanlan.zhihu.com/p/584671020
sort_values -https://zhuanlan.zhihu.com/p/584671020
df.sort_values(by=['Python成绩', '年龄'], axis=0, ascending=[False, True], inplace=True, na_position='last')
pivot
mulindex
pivot_table
cut、qcut
只设置分的箱子数时
qcut 基于分位数,所以基本每个箱子里的个数相同
cut 基于区间大小,所以基本每个箱子里的大小范围相同
cut可以自定义边界

cut
param:
q-箱子个数
bins-边界
label-新的箱子名
qcut
param:
q-箱子个数
label-新的箱子名

qcut
retbins=True , 可以返回边界,Whether to return the (bins, labels) or not.
_,bins=pd.qcut(a,3,labels=['yi','er','san'],retbins=True)
category -https://blog.csdn.net/superfjj/article/details/118305330
rolling
ffill
diff!!!!
df.diff(2)
向下移动两行后减去原列
cum

shift
pipe
reset_index
transform
复合索引列名的修改
svc、svr
SVC-分类
SVR-回归
predict_proba

二分类 计算roc

cls.predict_proba(t_x_test)[:,1]

多分类 计算roc

best_cls.predict_proba(m_x_test)
多分类评价指标
acc=accuracy_score(m_y_test,m_y_p)
recall=recall_score(m_y_test,m_y_p,average='micro')
precision=precision_score(m_y_test,m_y_p,average='micro')
f1=f1_score(m_y_test,m_y_p,average='micro')
auc=roc_auc_score(m_y_test,m_y_pro,multi_class='ovr')
输出格式控制
print('名字是 %s,年龄是%s' % (name ,age))
%6.3f
axis
数学计算时
axis=0 跨行 index,row series
axis=1 跨列 column
修改列名,通过index
离散化 -get_dummies、onehot
keras lstm-https://blog.csdn.net/qq_43703185/article/details/120494402
scoring参数输入
Classification
-f1
-f1_micro
Clustering
-rand_score
Regression
-neg_mean_absolute_error
-r2
-neg_mean_squared_error
heatmap形式 - https://www.cnblogs.com/ethan-wen/p/17405999.html,https://scikit-learn.org/stable/modules/model_evaluation.html#multimetric-scoring
where mask
seaborn heatmap
pie
特征选择、特征降维、长短、样本不平衡,离散化
长短
pivot_table
https://zhuanlan.zhihu.com/p/482192478

形成一个有列有行索引的表

列-index-groupby的by
行-value-groupby后挑选的列
计算-aggfunc-分组计算

melt
https://zhuanlan.zhihu.com/p/482192478

MultiIndex
https://blog.csdn.net/conving/article/details/120185108

index=[["a","a","b","b","c","c"],
["期末","期中","期末","期中","期末","期中"]]

names=["a","b","c"]
exems=["期中","期末"]
index=pd.MultiIndex.from_product([names,exems])

df3.set_index(["class","name"]) -列名

data1.sort_index(level=0,ascending=False)

shift,rolling
https://zhuanlan.zhihu.com/p/587349753?utm_id=0

计算差值

df_shift['one_week_net'] = df_shift.sales - df_shift.sales.shift(-7)
异常值->补全->标准化->降维/特征选择->采样
异常
-有nan
normal_=(((data-data.mean())/data.std()).abs()>3).any(axis=1)
-无nan
isf=IsolationForest(contamination=0.1)
isf.fit(dat2)
pre=isf.predict(dat2)
normal_=dat2.index[pre==-1]

补全
knn
kim=KNNImputer(n_neighbors=3)
dat1.loc[:,:]=kim.fit_transform(dat1)

降维
pca=PCA(n_components=2)//PCA(0.99)
s=StandardScaler()
pca_data.loc[:,:]=pca.fit_transform(s.fit_transform(data.iloc[:,:-1]))

特征选择
-有监督
feature_select=SelectKBest(mutual_info_regression,k=6)
feature_select.fit_transform(x_df,y_y_df)
x_df=x_df.loc[:,feature_select.get_support()]

-无监督
feature_select=VarianceThreshold(0.2)
feature_select.fit_transform(x_df)
x_df=x_df.loc[:,feature_select.get_support()]

onehot 哑变量
rain_data=pd.concat([train_data,pd.get_dummies(train_data['时间'].dt.quarter)],axis=1)
聚类绘图

posted @ 2024-07-28 17:27  xxxyyyxxxok  阅读(54)  评论(0)    收藏  举报