Pandas数据处理和数据展示

it2026-09-30  12

一.数据处理工具pandas和numpy

1.1 pandas读取数据

data = pd.read_csv("data.csv",index_col=False,encoding = "utf-8") data = pd.read_tabel("data.txt",sep = ",")

1.2 numpy.random 生成数据的用法

numpy.random.rand(4,2,3) ==>生成4*2*3的矩阵,其中元素在[0,1),float np.random.randn(4,2,3) ==>生成4*2*3的矩阵,元素是标准正态分布(以0为均值、以1为标准差的正态分布,记为N(0,1)),float np.random.randint(-5,5,size=(2,2)) ==>生成一个2*2的矩阵,元素值在[-5,5)随机整数,int np.random.random_sample(size=(2,2)) ==>生成一个2*2的矩阵,元素是[0,1),float np.random.seed(1676) ==>设置种子数,每次生成的随机数相同

1.3 pandas_profiling

用于简单快速查看数据分布和得到数据报告。

import pandas_profiling pfr = pandas_profiling.ProfileReport(data) pfr.to_file("./example.html")

1.4 pandas去掉重复项 df.drop_duplicates()

df[df.duplicated()].shape df = df.drop_duplicates() df.shape

1.5 pandas中loc和iloc区别

loc利用index的名称(这里可以是index和行号不一致),来获取想要的行(或列)。(名称导向的这个特点,使得df[df.loc[‘col_name’] == ‘condition’, ‘col_name’] = value_1成立。 具体的实际应用,可参考 代码案例 一步实现EXCEL的合并数据、数据筛选、数据透视功能。

iloc利用index的具体位置(所以它只能是整数型参数,行号),来获取想要的行(或列)。

# 这里loc就可以直接用自己写的索引来构成 df.loc['C':'6', '3':, -1] # 利用iloc抽取指定位置(所在的行整数值)的索引所构成的新的dataframe new_dataframe = df.iloc[index_list,:]

1.6 找到Nan值——np.isnan()

nan_np_list = np.argwhere(np.isnan(np_data))

1.7 哑变量生成——pd.get_dummies()

dummy_device_type = pd.get_dummies(data_org['platform'],prefix='device_type')

1.8 计算特征之间的相关系数

自变量之间相关系数较大的话,需要考虑共线性的问题,共线性会导致模型出现开式解,降低模型的稳定性。

常见方法有皮尔森相关系数和斯皮尔曼相关系数。两个系数都是介于-1和1之间,-1表示完全负相关,1表示完全正相关,0表示完全不相关。

使用皮尔森相关系数有局限:要求数据是成对的从正态分布中取得的。而斯皮尔曼相关系数是一种秩相关系数,不受数据分布的影响,它通过对变量排序,以排序后两个变量的秩次差来计算相关系数。

pearson = data.corr() # 适用于都是连续性变量 spearman = data.corr('spearman') # 适用于离散和连续变量

1.9 dataframe的拼接

df_all_row = concat([df1,df2]) #等价于 df1.append(df2),纵着拼接 #等价于 merge(df1,df2,left_index=True,right_index=True,how='outer') df_all_col = concat([df1,df2],axis=1) # 横着拼接

1.10 groupby的使用

df = pd.DataFrame({'A': ['a', 'b', 'a', 'c', 'a', 'c', 'b', 'c'], 'B': [2, 8, 1, 4, 3, 2, 5, 9], 'C': [102, 98, 107, 104, 115, 87, 92, 123]}) df.groupby('A').mean() ==> A B C a 2.0 108.000000 b 6.5 95.000000 c 5.0 104.666667

1.11 Series.apply

该函数用于对该series的所有元素进行处理生成一个新的series。

new_series = pd.Series([i for i in range(10)]).apply(lambda x:x**2) """这里是函数中带2个参数的""" def subtract_custom_value(x, custom_value): return x - custom_value new_series_2 = df.apply(subtract_custom_value, args=(5,))

1.12 Series可以直接用于2个列相加减

a = pd.Series([i for i in range(10)]) b = pd.Series([i+1 for i in range(10)]) diff_series = a - b

1.13 sort_values将dataframe根据某一列顺序重新生成

# 比如这里需要将整个dataframe根据时间戳的顺序(True)进行重新调整 data = data.sort_values(by = ['timestamp'],ascending=True)

1.14 concat 将Dataframe或者是Series进行合并

data = pd.concat([x1,x2,x3],axis=1) # 这里是三个Series根据每个的index进行合并(按列)

1.15 Series.reset_index 直接将Series转成Dataframe

df = series.reset_index(name = 'index_name') # 这里给series的index设置名字为'index_name',并变成一列

1.16 df.groupby()的apply方式使用

# 初始的dataframe df = pd.DataFrame({'A': 'a a b'.split(), 'B': [1,2,3], 'C': [4,6, 5]}) g = df.groupby('A') print(g.apply(lambda x: x / x.sum())) B C 0 0.333333 0.4 1 0.666667 0.6 2 1.000000 1.0 print(g.apply(list)) B C 0 [1,2] [3] 1 [4,6] [5]

1.17 df.groupby() 直接分成2个组的dataframe

df = pd.DataFrame({'A': 'a a b'.split(), 'B': [1,2,3], 'C': [4,6, 5]}) g = df.groupyby('A') for name,group in g: name_i = name df_i = group # 这里就是A只有a的dataframe

二.绘图查看数据分布——seaborn和matplotlib

2.1 频数分布直方图

def plot_bar(x,y,color,title,width = 0.5): plt.figure() idx = np.arange(len(x)) plt.bar(idx,y,width,color = color) for xx, yy in zip(x, y): plt.text(xx, yy + 0.1, str('%.2f%%' % ((yy/np.array(y).sum())*100)), ha='center') plt.xticks(idx,x) plt.title(title) plt.xlabel('Hour') plt.ylabel('Trade-Frequence') plt.show() mu, sigma = 100, 15 x = mu + sigma * np.random.randn(10000) # the histogram of the data n, bins, patches = plt.hist(x, 50, density=1, facecolor='g', alpha=0.75) plt.xlabel('Smarts') plt.ylabel('Probability') plt.title('Histogram of IQ') plt.text(60, .025, r'$\mu=100,\ \sigma=15$') plt.axis([40, 160, 0, 0.03]) plt.grid(True) plt.show()

2.2 散点图

plt.plot(x,y)

2.3 直线图

plt.scatter(x,y)

2.4 双变量分布图

def two_dims_draw_relationship(df,xlabel,ylabel): # 双变量分布 x,ylabel是字符串,df必须是双维度的dataframe sns.set(color_codes=True) g = sns.jointplot(x=xlabel, y=ylabel, data=df, kind="kde", color="y") g.plot_joint(plt.scatter, c="m", s=30, linewidth=1, marker="+") g.ax_joint.collections[0].set_alpha(0) # 画背景网格线 g.set_axis_labels("${}$".format(xlabel), "${}$".format(ylabel)) plt.show()

2.5 多变量两两之间的分布图

def all_two_feature_distribution(df = sns.load_dataset('iris')): sns.set(style="ticks") sns.pairplot(df, hue="species") plt.show()

2.6 热度图

scores_h = pd.DataFrame(np.array(scores_h).reshape(18, 3)) scores_h.index = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19] scores_h.columns = [1,2,3] plt.figure() ax = sns.heatmap(scores_h, annot=True,xticklabels=cols_all_features, yticklabels=cols_all_features,fmt='.2f') plt.ylabel("N_cluster") plt.xlabel("linkages") # 必须先savefig,之后再show,就不会出现保存时白色图片了 plt.savefig("h.jpg") plt.show()

喜欢我的文章,还请大大们关注一波,当然可以直接访问我的主页:lixiaofei2yy.website

最新回复(0)