Pandas的21-50题

本文档演示了如何使用Python的pandas库读取Excel数据,进行数据转换、分组计算、时间格式化、数值统计、数据分桶、数据合并等操作。涉及到的技能包括数据清洗、数据类型转换、数据可视化及数据分组分析。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

# 21.读取本地EXCEL数据
import numpy as np
import pandas as pd
df = pd.read_excel('pandas120.xlsx')
df
createTimeeducationsalary
02020-03-16 11:30:18本科20k-35k
12020-03-16 10:58:48本科20k-40k
22020-03-16 10:46:39不限20k-35k
32020-03-16 10:45:44本科13k-20k
42020-03-16 10:20:41本科10k-20k
............
1302020-03-16 11:36:07本科10k-18k
1312020-03-16 09:54:47硕士25k-50k
1322020-03-16 10:48:32本科20k-40k
1332020-03-16 10:46:31本科15k-23k
1342020-03-16 11:19:38本科20k-40k

135 rows × 3 columns

# 22.查看df数据前5行
df.head()
df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 135 entries, 0 to 134
Data columns (total 3 columns):
 #   Column      Non-Null Count  Dtype         
---  ------      --------------  -----         
 0   createTime  135 non-null    datetime64[ns]
 1   education   135 non-null    object        
 2   salary      135 non-null    object        
dtypes: datetime64[ns](1), object(2)
memory usage: 3.3+ KB
# 23.将salary列数据转换为最大值与最小值的平均值

# 第一种方法,使用函数
import re
# 方法一:apply + 自定义函数
def func(df):
    lst = df['salary'].split('-')
    smin = int(lst[0].strip('k'))
    smax = int(lst[1].strip('k'))
    df['salary'] = int((smin + smax) / 2 * 1000)
    return df

df = df.apply(func,axis=1)

# 24.将数据根据学历进行分组并计算平均薪资
# 第一种方法
print(df.groupby('education').mean())

# 第二种方法
df.groupby('education').agg({'salary':np.mean})
                 salary
education              
不限         19600.000000
大专         10000.000000
本科         19361.344538
硕士         20642.857143
salary
education
不限19600.000000
大专10000.000000
本科19361.344538
硕士20642.857143
# 25.将createTime列时间转换为月-日

## 第一种方法
# for i in range(len(df)):
#         df.iloc[i,0] = df.iloc[i,0].to_pydatetime().strftime("%m-%d")        
# df.head()

## 第二种方法
# df['时间'] = df['createTime'].astype("string")
# df['时间'] = df['时间'].str[5:10]
# df.head()

# 第三种方法
df['createTime'] = df['createTime'].dt.strftime("%m-%d")
df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 135 entries, 0 to 134
Data columns (total 3 columns):
 #   Column      Non-Null Count  Dtype 
---  ------      --------------  ----- 
 0   createTime  135 non-null    object
 1   education   135 non-null    object
 2   salary      135 non-null    int64 
dtypes: int64(1), object(2)
memory usage: 3.3+ KB
# 26.查看索引、数据类型和内存信息
df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 135 entries, 0 to 134
Data columns (total 3 columns):
 #   Column      Non-Null Count  Dtype 
---  ------      --------------  ----- 
 0   createTime  135 non-null    object
 1   education   135 non-null    object
 2   salary      135 non-null    int64 
dtypes: int64(1), object(2)
memory usage: 3.3+ KB
# 27.查看数值型列的汇总统计
df.describe()
salary
count135.000000
mean19159.259259
std8661.686922
min3500.000000
25%14000.000000
50%17500.000000
75%25000.000000
max45000.000000
# 28.新增一列根据salary将数据分为三组
# 数据分桶

bins = [0,5000,20000,50000]
group_names = ['低','中','高']
df['type'] = pd.cut(df['salary'],bins,labels =group_names )
df
createTimeeducationsalarytype
003-16本科27500
103-16本科30000
203-16不限27500
303-16本科16500
403-16本科15000
...............
13003-16本科14000
13103-16硕士37500
13203-16本科30000
13303-16本科19000
13403-16本科30000

135 rows × 4 columns

# 29.按照salary列对数据降序排列
df.sort_values('salary',ascending=False)

# 将salary进行降序排列,并将其生成列表
a = df['salary'].sort_values(ascending=False).to_list()
# 30.取出第33行数据

# iloc和loc的区别
# 还有更多的经过pandas优化过的选择方式:
# df.loc 通过标签索引行数据
# df.iloc 通过位置获取行数据


# df.iloc[32]
df.loc[32]
createTime    03-16
education        硕士
salary        22500
type              高
Name: 32, dtype: object
# 31.计算salary列的中位数
df['salary'].median()

# 或者网上给予的方法,是调用numpy的中位数方法来进行操作
np.median(df['salary'])
17500.0
# 32.绘制薪资水平频率分布直方图
df['salary'].plot(kind='hist')

在这里插入图片描述

# 33.绘制薪资水平密度曲线
# xlim参数中填写的是横轴的范围。

df['salary'].plot(kind = 'kde',xlim=(0,80000))

在这里插入图片描述

# 34.删除最后一列categories

# 第一种方法直接进行删除
# del df['type']

# 第二种方法,使用drop进行删除
# 1. df= df.drop('column_name', 1)
df = df.drop('type',1)  #删除不改表原始数据

#2.df.drop('columns',axis=1,inplace='True') #改变原始数据
# 35.将df的第一列与第二列合并为新的一列

# 第一种方法,将两列进行直接相加
df['new_columns'] = df['createTime'] + df['education']

# 第二种方法,是使用cat函数进行拼接
df['new_columns'] = df['createTime'].str.cat(df['education'])
# 36.将education列与salary列合并为新的一列

# 第一种方法,使用astype()函数进行数据类型的转换 
df['test'] = df['education'] + df['salary'].astype('str')

# 第二种方法,使用map函数进行每行都进行数据类型的一种转换
df['test'] = df['education'] + df['salary'].map(str)
df
createTimeeducationsalarynew_columnstest
003-16本科2750003-16本科本科27500
103-16本科3000003-16本科本科30000
203-16不限2750003-16不限不限27500
303-16本科1650003-16本科本科16500
403-16本科1500003-16本科本科15000
..................
13003-16本科1400003-16本科本科14000
13103-16硕士3750003-16硕士硕士37500
13203-16本科3000003-16本科本科30000
13303-16本科1900003-16本科本科19000
13403-16本科3000003-16本科本科30000

135 rows × 5 columns

# 37.计算salary最大值与最小值之差
chazhi = df['salary'].max() - df['salary'].min()
chazhi
41500
# 38.将第一行与最后一行拼接
pd.concat([df[:1], df[-2:-1]])
createTimeeducationsalarynew_columnstest
003-16本科2750003-16本科本科27500
13303-16本科1900003-16本科本科19000
# 39.将第8行数据添加至末尾
df.append(df.iloc[7])
createTimeeducationsalarynew_columnstest
003-16本科2750003-16本科本科27500
103-16本科3000003-16本科本科30000
203-16不限2750003-16不限不限27500
303-16本科1650003-16本科本科16500
403-16本科1500003-16本科本科15000
..................
13103-16硕士3750003-16硕士硕士37500
13203-16本科3000003-16本科本科30000
13303-16本科1900003-16本科本科19000
13403-16本科3000003-16本科本科30000
703-16本科1250003-16本科本科12500

136 rows × 5 columns

# 40.查看每列的数据类型
df.dtypes
createTime     object
education      object
salary          int64
new_columns    object
test           object
dtype: object
# 41.将createTime列设置为索引
df.set_index("createTime")
educationsalarynew_columnstest
createTime
03-16本科2750003-16本科本科27500
03-16本科3000003-16本科本科30000
03-16不限2750003-16不限不限27500
03-16本科1650003-16本科本科16500
03-16本科1500003-16本科本科15000
...............
03-16本科1400003-16本科本科14000
03-16硕士3750003-16硕士硕士37500
03-16本科3000003-16本科本科30000
03-16本科1900003-16本科本科19000
03-16本科3000003-16本科本科30000

135 rows × 4 columns

# 42.生成一个和df长度相同的随机数dataframe
df1 = pd.DataFrame(pd.Series(np.random.randint(1, 10, 135)))
df1
0
03
19
27
35
43
......
1302
1313
1326
1333
1347

135 rows × 1 columns

# 43.将上一题生成的dataframe与df合并
df= pd.concat([df,df1],axis=1)
df
createTimeeducationsalarynew_columnstest0
003-16本科2750003-16本科本科275003
103-16本科3000003-16本科本科300009
203-16不限2750003-16不限不限275007
303-16本科1650003-16本科本科165005
403-16本科1500003-16本科本科150003
.....................
13003-16本科1400003-16本科本科140002
13103-16硕士3750003-16硕士硕士375003
13203-16本科3000003-16本科本科300006
13303-16本科1900003-16本科本科190003
13403-16本科3000003-16本科本科300007

135 rows × 6 columns

# 44.生成新的一列new为salary列减去之前生成随机数列
df["new"] = df["salary"] - df[0]
df
createTimeeducationsalarynew_columnstest0new
003-16本科2750003-16本科本科27500327497
103-16本科3000003-16本科本科30000929991
203-16不限2750003-16不限不限27500727493
303-16本科1650003-16本科本科16500516495
403-16本科1500003-16本科本科15000314997
........................
13003-16本科1400003-16本科本科14000213998
13103-16硕士3750003-16硕士硕士37500337497
13203-16本科3000003-16本科本科30000629994
13303-16本科1900003-16本科本科19000318997
13403-16本科3000003-16本科本科30000729993

135 rows × 7 columns

# 45.检查数据中是否含有任何缺失值
df.isnull().values.any()
False
# 46.将salary列类型转换为浮点数
df['salary'] = df['salary'].astype('float')
df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 135 entries, 0 to 134
Data columns (total 7 columns):
 #   Column       Non-Null Count  Dtype  
---  ------       --------------  -----  
 0   createTime   135 non-null    object 
 1   education    135 non-null    object 
 2   salary       135 non-null    float64
 3   new_columns  135 non-null    object 
 4   test         135 non-null    object 
 5   0            135 non-null    int32  
 6   new          135 non-null    int64  
dtypes: float64(1), int32(1), int64(1), object(4)
memory usage: 7.0+ KB
# 47.计算salary大于10000的次数
aa = df[df['salary']>10000]

# 第一种方法
aa.shape[0]

# 第二种方法
len(aa)

# 第三种方法
aa.count()[0]
119
# 48.查看每种学历出现的次数
df['education'].value_counts()
本科    119
硕士      7
不限      5
大专      4
Name: education, dtype: int64
# 49.查看education列共有几种学历
# 第一种方法
len(df['education'].value_counts())

# 第二种方法
df['education'].nunique()

# 第三种方法
len(df['education'].unique())
4
# 50.提取salary与new列的和大于60000的最后3行
# 自己做的比较简单的方法
df[df['salary'] + df['new'] >= 60000].iloc[-3:]

# 网上答案 比较麻烦的做法
df1 = df[['salary','new']]
rowsums = df1.apply(np.sum, axis=1)
res = df.iloc[np.where(rowsums > 60000)[0][-3:], :]
res
createTimeeducationsalarynew_columnstest0new
9203-16本科35000.003-16本科本科35000734993
10103-16本科37500.003-16本科本科37500737493
13103-16硕士37500.003-16硕士硕士37500337497
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值