暑期实践第二十三天 2022-7-26

1.数据移位

shift方法

DataFrame.shift(periods=1, freq=None, axis=0)

periods:表示移动的幅度,可以是正数,也可以是负数,默认值是1,1表示移动一次,注意这里移动的都是数据,而索引是不移动的。移动之后没有对应值的,就被赋值为NaN.

freq:可选参数,默认值为None,只适用于时间序列,如果这个参数存在,那么会按照参数值来移动时间索引,而数据值不会发生变化。

axis:axis=1表示列,axis=0表示行,默认值为0.

import pandas as pd
data = [110, 105, 99, 120, 115]
index = [1, 2, 3, 4, 5]
df = pd.DataFrame(data=data, index=index, columns=['英语'])
df['升降'] = df['英语'] - df['英语'].shift()
print(df)

输出结果

    英语    升降
1  110   NaN
2  105  -5.0
3   99  -6.0
4  120  21.0
5  115  -5.0

2.数据转换

2.1一列数据转换为多列数据

split方法

pandas的DataFrame对象中的str.split内置方法可以实现分割字符串

Series.str.split(pat=None, n=-1, expand=False)

pat:字符串、符号或正则表达式,表示字符串分割的依据,默认以空格分割字符串。

n:整型,分割次数,默认值是-1。 0或-1都将返回所有拆分的字符串。

expand:布尔型,分割后的结果是否转换为DataFrame,默认值是False

import pandas as pd
pd.set_option('display.max_columns', 500)
pd.set_option('display.width', 1000)
pd.set_option('display.unicode.east_asian_width', True)
df = pd.read_excel('mrbooks.xls', usecols=['买家会员名', '收货地址'])
series = df['收货地址'].str.split(' ', expand=True)
df['省']=series[0]
df['市']=series[1]
df['区']=series[2]
print(df.head())

输出结果

  买家会员名                                                             收货地址      省      市      区
0    mr00001                                重庆 重庆市 南岸区                       重庆  重庆市  南岸区
1    mr00003      江苏省 苏州市 吴江区 吴江经济技术开发区亨通路                    江苏省  苏州市  吴江区
2    mr00004  江苏省 苏州市 园区 苏州市工业园区唯亭镇阳澄湖大道维纳阳光花园......  江苏省  苏州市    园区
3    mr00002   重庆 重庆市 南岸区 长生桥镇茶园新区长电路11112号                      重庆  重庆市  南岸区
4    mr00005           安徽省 滁州市 明光市 三界镇中心街10001号                    安徽省  滁州市  明光市

join方法与split方法结合

通过join方法与split方法结合,以逗号分割宝贝标题

import pandas as pd
pd.set_option('display.max_columns', 500)
pd.set_option('display.width', 1000)
pd.set_option('display.unicode.east_asian_width', True)
df = pd.read_excel('mrbooks.xls', usecols=['买家会员名', '宝贝标题'])
df = df.join(df['宝贝标题'].str.split(',', expand=True))
print(df.head())

输出结果

  买家会员名                                                                         宝贝标题                    0                  1                           2                            3     4     5
0    mr00001                                PHP程序员开发资源库                                PHP程序员开发资源库               None                        None                         None  None  None
1    mr00003                                 个人版编程词典加点                                 个人版编程词典加点               None                        None                         None  None  None
2    mr00004                                               邮费                                               邮费               None                        None                         None  None  None
3    mr00002  零基础学Java全彩版 ,Java精彩编程200例,Java项目开发实战入门全彩版,明日科技...  零基础学Java全彩版   Java精彩编程200例  Java项目开发实战入门全彩版  明日科技 Java编程词典个人版  None  None
4    mr00005                                  零基础学PHP全彩版                                  零基础学PHP全彩版               None                        None                         None  None  None

注意分割的逗号是中文输入法

将DataFrame中的tuple(元组)类型数据分割成多列

import pandas as pd
pd.set_option('display.unicode.east_asian_width', True)
df = pd.DataFrame({'a':[1, 2, 3, 4, 5], 'b':[(1, 2), (3, 4), (5, 6), (7, 8), (9, 10)]})
print(df)
df[['b1', 'b2']] = df['b'].apply(pd.Series)
print(df)

运行结果

   a        b
0  1   (1, 2)
1  2   (3, 4)
2  3   (5, 6)
3  4   (7, 8)
4  5  (9, 10)
   a        b  b1  b2
0  1   (1, 2)   1   2
1  2   (3, 4)   3   4
2  3   (5, 6)   5   6
3  4   (7, 8)   7   8
4  5  (9, 10)   9  10

2.2行列转换

在Pandas处理数据的过程中,有时需要对数据进行行列转换或重排,这时主要使用stack方法、unstack方法、和pivot方法。

stack方法

stack方法用于将原来的列索引转换成最内层的行索引

DataFrame.stack(level=-1, dropna=True)
import pandas as pd
pd.set_option('display.max_columns', 500)
pd.set_option('display.width', 1000)
pd.set_option('display.unicode.east_asian_width', True)
df = pd.read_excel('grade.xls')
print(df)
df = df.set_index(['班级', '序号'])    #设置二级索引
df = df.stack()
print(df)

输出结果

    序号 班级   姓名  得分  排名
0      1  1班  王*亮    84    11
1      2  1班   杨**    82    17
2      3  1班  王*彬    78    37
3      4  2班  赛*琪    77    51
4      5  2班   刘**    76    64
5      6  2班  刘*彤    74    89
6      7  3班  张*扬    72   115

班级  序号
1班   1     姓名    王*亮
            得分       84
            排名       11
      2     姓名     杨**
            得分       82
            排名       17
      3     姓名    王*彬
            得分       78
            排名       37
2班   4     姓名    赛*琪
            得分       77
            排名       51
      5     姓名     刘**
            得分       76
            排名       64
      6     姓名    刘*彤
            得分       74
            排名       89
3班   7     姓名    张*扬
            得分       72
            排名      115

unstack方法

unstack方法与stack方法相反,它是stack方法的逆操作,即将最内层的行索引转换为列索引

语法同stack

df=pd.read_excel('grade.xls',sheet_name='英语2')      #导入Excel文件
print(df)
df = df.set_index(['班级','序号','Unnamed: 2'])       #设置多级索引
print(df.unstack())

输出结果

   班级  序号 Unnamed: 2 Unnamed: 3
0   1班     1       姓名      王*亮
1   1班     1       得分         84
2   1班     1       排名         11
3   1班     2       姓名       杨**
4   1班     2       得分         82
5   1班     2       排名         17
6   1班     3       姓名      王*彬
7   1班     3       得分         78
8   1班     3       排名         37
9   2班     4       姓名      赛*琪
10  2班     4       得分         77
11  2班     4       排名         51
12  2班     5       姓名       刘**
13  2班     5       得分         76
14  2班     5       排名         64
15  2班     6       姓名      刘*彤
16  2班     6       得分         74
17  2班     6       排名         89
           Unnamed: 3
Unnamed: 2       姓名 得分 排名
班级 序号
1班  1          王*亮   84   11
     2           杨**   82   17
     3          王*彬   78   37
2班  4          赛*琪   77   51
     5           刘**   76   64
     6          刘*彤   74   89

在unstack方法中有一个参数可以指定转换第几层索引。例如,unstack(0)就是把第一层行索引转换为列索引,默认是将最内层索引转换为列索引。

pivot方法

pivot方法针对列的值,即指定某列的值作为行索引,指定某列的值作为列索引,然后再指定哪些列作为索引对应的值。unstack方法针对索引进行操作:pivot方法针对值进行操作。但实际上,两者在功能方面往往可以互相实现。

DaraFrame.pivot(index=None, columns=None, values=None)

values:列用于填充新DataFrame数据的值,如果未指定,则将使用所有剩余的列,结果将具有分层索引列。

import pandas as pd
#设置数据显示的列数和宽度
pd.set_option('display.max_columns',500)
pd.set_option('display.width',1000)
#解决数据输出时列名不对齐的问题
pd.set_option('display.unicode.east_asian_width', True)
df=pd.read_excel('grade.xls',sheet_name='英语3')      #导入Excel文件
print(df)
print(df.pivot(index='序号',columns='班级',values='得分'))

输出结果

    序号 班级   姓名  得分  排名
0      1  1班  王*亮    84    11
1      2  1班   杨**    82    17
2      3  1班  王*彬    78    37
3      1  2班  赛*琪    77    51
4      2  2班   刘**    76    64
5      3  2班  刘*彤    74    89
6      1  3班  张*扬    72   115
7      2  3班   尹**    72   115
8      3  3班  李*旸    72   115
9      1  4班  *华煦    72   115
10     2  4班  于*明    72   115
11     3  4班  袁*皓    70   151
12     1  5班    姜*    70   151
13     2  5班   窦**    68   195
14     3  5班  张*昕    68   195
班级  1班  2班  3班  4班  5班
序号
1      84   77   72   72   70
2      82   76   72   72   68
3      78   74   72   70   68

2.3DataFrame转换为字典

将DataFrame转换为字典主要使用DataFrame对象中的to_dict方法,以索引作为字典的键(key),以列作为字典的值。

import pandas as pd
df = pd.read_excel('mrbooks.xls')
df1=df.groupby(['宝贝标题'])['宝贝总数量'].sum().head()
mydict = df1.to_dict()
for i, j in mydict.items():
    print(i, ':\t', j)
ASP.NET项目开发实战入门全彩版 :    32
ASP.NET项目开发实战入门全彩版,ASP.NET全能速查宝典 :     2
Android学习黄金组合套装 :    4
Android项目开发实战入门 :    1
C#+ASP.NET项目开发实战入门全彩版 :     1

2.4DataFrame转换为列表

主要使用tolist方法

import pandas as pd
df = pd.read_excel('mrbooks.xls')
df1 = df[['买家会员名']].head()
list1 = df1['买家会员名'].values.tolist()
for s in list1:
    print(s)

输出结果

mr00001
mr00003
mr00004
mr00002
mr00005

2.5DataFrame转化为元组

首先通过循环语句按行读取DataFrame数据,然后使用元组函数tuple将其转换为元组。

import pandas as pd
df = pd.read_excel('fls.xls')
df1 = df[['label1', 'labbel2']].head()
tuples = [tuple(x) for x in dfi.values]
for t in tuples:
    print(t)

2.6Excel转换为HTML网页格式

使用to_html方法来导出

import pandas as pd
df=pd.read_excel('mrbooks.xls',usecols=['买家会员名','宝贝标题']).head()
df.to_html('mrbooks.html',header = True,index = False)

Original: https://blog.csdn.net/m0_63619203/article/details/125990343
Author: 亦晓高
Title: 暑期实践第二十三天 2022-7-26

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/738987/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球