Pandas—DataFrame高阶函数(一)

上一篇:Pandas—DataFrame的读取、保存、增、删、查、改

1、DataFrame排序

2、DataFrame的元素计算

3、DataFrame对象合并

4、DataFrame设置索引和还原

5、去除特定列下面的重复行

6、分类变量(categorical variable)转换为“哑变量矩阵”(dummy matrix)或“指标矩阵”(indicator matrix)


1、DataFrame排序

(1)按单列、按多列排序

df
   col1  col2  col3
b     4     6     5
a     1     3     2
c     7     9     8

# 按第一列升序
df.sort_values(by = 'col1',axis = 0,ascending = True,inplace = True)
print (df)
   col1  col2  col3
a     1     3     2
b     4     6     5
c     7     9     8

# 按第一列降序
df.sort_values(by = 'col1',axis = 0,ascending = False,inplace = True)
print (df)
   col1  col2  col3
c     7     9     8
b     4     6     5
a     1     3     2

df
   a  b  c
0  9  4  6
1  2  7  5
2  5 -3  8
3  1  2  3
4  0  2  4
5  7  2  4

# 按照b,c,a的列顺序升序排序
df.sort_values(by = ['b','c','a'],axis = 0,ascending = True,inplace = True)
print (df)
   a  b  c
2  5 -3  8
3  1  2  3
4  0  2  4
5  7  2  4
0  9  4  6
1  2  7  5

注:inplace指定为True时,表示会直接对df中的数据进行排序,函数返回值为None。如果不设置为True(默认为false),则不会对df中数据进行修改,会返回一个新的排序后的df。 

(2)按行排序(即按列标题名排序)

df
   col2  col1  col3
b     4     6     5
a     1     3     2
c     7     9     8

# 按行升序(按列标题名来排序)
df.sort_index(axis = 1,ascending = True, inplace =True)
print (df)
   col1  col2  col3
b     6     4     5
a     3     1     2
c     9     7     8

# 按行降序
df.sort_index(axis = 1,ascending = False, inplace =True)
print (df)
   col3  col2  col1
b     5     4     6
a     2     1     3
c     8     7     9

2、DataFrame的元素计算

   df2.sum()    # 默认是对每列元素求和
   df2.sum(1)   # 行求和
   df2.apply(lambda x:x*2)   # 对每个元素乘以2
   df2**2    # 对每个元素求平方

df
   col2  col1  col3
b     4     6     5
a     1     3     2
c     7     9     8

# 默认是对每列元素求和
print (df.sum()) 
col2    12
col1    18
col3    15 

# 每行元素求和  
print (df.sum(1))
b    15
a     6
c    24
dtype: int64   

# 对每个元素乘以2
print (df2.apply(lambda x:x*2))
   col2  col1  col3
b     8    12    10
a     2     6     4
c    14    18    16   

# 对每个元素求平方
print (df2**2)    
   col2  col1  col3
b    16    36    25
a     1     9     4
c    49    81    64

3、DataFrame对象合并

(1)DataFrame.join()基于索引(索引作为主键)或关键列(该列作为主键)与其它DataFrame的列合并到一起。

函数原型:
  DataFrame.join(other, on=None, how='left', lsuffix='', rsuffix='', sort=False)
参数:
  other : DataFrame, 带名字的Series或者DataFrame的列表。所有的DataFrame的索引应该相同,如果传入的类型为Series,那么它的名字属性应该被指定。
  on : 列名称,或者列名称的list/tuple,或者类似形状的数组。连接的列,默认使用索引连接。
  how : 指的是合并(连接)的方式有inner(内连接),left(左外连接),right(右外连接),outer(全外连接);默认为left。
  lsuffix : string,当左右两个表的列名有重复时,用于左边表列名的前缀。
  rsuffix : string,当左右两个表的列名有重复时,用于右边表列名的前缀。
  sort : boolean, 默认为False,根据join的键值对结果进行排序,设置为False可以提高性能。
注意:当传入一个DataFrame的列表时,并不支持on,lsuffix,rsuffix这三个选项。

实例:

caller
    A key
0  A0  K0
1  A1  K1
2  A2  K2
3  A3  K3
4  A4  K4
5  A5  K5
other
    B key
0  B0  K0
1  B1  K1
2  B2  K2

# 默认使用索引连接,默认连接方式how = left,即左外连接
join = caller.join(other, lsuffix='_caller', rsuffix='_other')
print (join)
    A key_caller    B key_other
0  A0         K0   B0        K0
1  A1         K1   B1        K1
2  A2         K2   B2        K2
3  A3         K3  NaN       NaN
4  A4         K4  NaN       NaN
5  A5         K5  NaN       NaN

# 如果使用关键列连接,此时我们需要在caller和other中设置关键字作为索引
join = caller.set_index('key').join(other.set_index('key'))
print (join)
      A    B
key         
K0   A0   B0
K1   A1   B1
K2   A2   B2
K3   A3  NaN
K4   A4  NaN
K5   A5  NaN

# 或者
join = caller.join(other.set_index('key'), on='key')
print (join)
    A key    B
0  A0  K0   B0
1  A1  K1   B1
2  A2  K2   B2
3  A3  K3  NaN
4  A4  K4  NaN
5  A5  K5  NaN

(2)pandas.merge()通过一个或多个键将两个关系表连接起来,类似于 SQL 中的 JOIN

函数原型:
  DataFrame.merge(right, how='inner', on=None, left_on=None, right_on=None, left_index=False, right_index=False, sort=False, suffixes=('_x', '_y'), copy=True, indicator=False, validate=None)
函数参数:
  right : DataFrame对象
  how : 指的是合并(连接)的方式有inner(内连接),left(左外连接),right(右外连接),outer(全外连接);默认为inner。
  on : 指明用于连接键名称。必须存在右右两个DataFrame对象中,如果没有指定且其他参数也未指定则以两个DataFrame的列名交集做为连接键。
  left_on : 左侧DataFrame中用作连接键的列;
  right_on : 右侧DataFrame中用作连接键的列;
  left_index : boolean, 默认为False。是否将左侧的行索引用作其连接键;
  right_index : boolean,默认为False。是否将右侧的行索引用作其连接键;
  sort : boolean, 默认为False。在大多数情况下设置为False可以提高性能
  suffixes : 长度为2的序列(tuple, list等).字符串值组成的元组,用于指定当左右DataFrame存在相同列名时在列名后面附加的后缀名称,默认为('_x','_y');
  copy : boolean, 默认为True。默认为True。如果设置为False,可以避免将数据复制到结果数据结构中
  indicator : boolean or string, 默认为False。在输出的DataFrame中增加名为"_merge"的一列,用于显示合并数据中来源情况。
比如显示为:left,left_only,right,right_only,both等。
  validate : string,默认为None。如果指定,则检查合并是否属于指定类型。
     “one_to_one” or “1:1”: 检查左右两个数据集中合并的键是否唯一。
     “one_to_many” or “1:m”: 检查在右边数据集中的键是否唯一。
     “many_to_one” or “m:1”:检查左边数据集中的键是否唯一。
     “many_to_many” or “m:m”: 不做任何检查。

实例:

left
    A   B key1 key2
0  A0  B0   K0   K0
1  A1  B1   K0   K1
2  A2  B2   K1   K0
3  A3  B3   K2   K1
right
    A   B key1 key2
0  A0  B0   K0   K0
1  A1  B1   K0   K1
2  A2  B2   K1   K0
3  A3  B3   K2   K1

#没有指定how的话默认使用inner方法
merged = pd.merge(left, right, on=['key1', 'key2'])
print (merged)
    A   B key1 key2   C   D
0  A0  B0   K0   K0  C0  D0
1  A2  B2   K1   K0  C1  D1
2  A2  B2   K1   K0  C2  D2

merged = pd.merge(left, right, how='left', on=['key1', 'key2'])
print (merged)
    A   B key1 key2    C    D
0  A0  B0   K0   K0   C0   D0
1  A1  B1   K0   K1  NaN  NaN
2  A2  B2   K1   K0   C1   D1
3  A2  B2   K1   K0   C2   D2
4  A3  B3   K2   K1  NaN  NaN

merged = pd.merge(left, right, how='right', on=['key1', 'key2'])
print (merged)
     A    B key1 key2   C   D
0   A0   B0   K0   K0  C0  D0
1   A2   B2   K1   K0  C1  D1
2   A2   B2   K1   K0  C2  D2
3  NaN  NaN   K2   K0  C3  D3

merged = pd.merge(left, right, how='outer', on=['key1', 'key2'])
print (merged)
     A    B key1 key2    C    D
0   A0   B0   K0   K0   C0   D0
1   A1   B1   K0   K1  NaN  NaN
2   A2   B2   K1   K0   C1   D1
3   A2   B2   K1   K0   C2   D2
4   A3   B3   K2   K1  NaN  NaN
5  NaN  NaN   K2   K0   C3   D3

merged = pd.merge(left, right, left_on='key1', right_on='key2')
print (merged)
    A   B key1_x key2_x   C   D key1_y key2_y
0  A0  B0     K0     K0  C0  D0     K0     K0
1  A0  B0     K0     K0  C1  D1     K1     K0
2  A0  B0     K0     K0  C2  D2     K1     K0
3  A0  B0     K0     K0  C3  D3     K2     K0
4  A1  B1     K0     K1  C0  D0     K0     K0
5  A1  B1     K0     K1  C1  D1     K1     K0
6  A1  B1     K0     K1  C2  D2     K1     K0
7  A1  B1     K0     K1  C3  D3     K2     K0

# 将左边行索引作为连接键
merged = pd.merge(left, right, left_on='key1', right_on='key2', left_index=True)
print (merged)
    A   B key1_x key2_x   C   D key1_y key2_y
0  A0  B0     K0     K0  C0  D0     K0     K0
1  A0  B0     K0     K0  C1  D1     K1     K0
2  A0  B0     K0     K0  C2  D2     K1     K0
3  A0  B0     K0     K0  C3  D3     K2     K0
0  A1  B1     K0     K1  C0  D0     K0     K0
1  A1  B1     K0     K1  C1  D1     K1     K0
2  A1  B1     K0     K1  C2  D2     K1     K0
3  A1  B1     K0     K1  C3  D3     K2     K0

(3)pandas.concat()可横向按行合并,可纵向按列合并

函数原型:
pd.concat(objs, axis=0, join='outer', join_axes=None, ignore_index=False,
          keys=None, levels=None, names=None, verify_integrity=False,
          copy=True)
函数参数:
  objs : 待合并的对象集合,可以是Series,DataFrame
  axis : {0, 1, …}, 默认为0. 需要合并链接的轴,0是行,1是列. 
  join : 连接的方式‘inner’或者‘outer’, 默认为 ‘outer’。inder得到两表交集,outer得到两表并集
  ignore_index : boolean,默认为False. 按哪些对象的索引保存;
  join_axes : {False,True},是否忽略原 index,默认为不忽略。
  keys : sequence, 默认为None. 为原始DataFrame添加一个键。
  levels : list of sequences, default None. Specific levels (unique values) to use for constructing a MultiIndex. Otherwise they will be inferred from the keys.
  names : list, default None. Names for the levels in the resulting hierarchical index.
  verify_integrity : boolean, 默认为False.  检查concat后的结果中是否包含重复项. 这个操作非常效率很低。
  copy : boolean, 默认为True. 总是将数据复制到数据结构中;大多数情况下设置为False可以提高性能。

实例1,按列合并(纵向合并):

df1
  letter  number
0      a       1
1      b       2
df2
  letter  number
0      c       3
1      d       4
df3
  letter  number animal
0      c       3    cat
1      d       4    dog

# 合并df1和df2,默认连接方式为outer
concated = pd.concat([df1, df2])
print (concated)
  letter  number
0      a       1
1      b       2
0      c       3
1      d       4

# 合并df1和df3,默认连接方式为outer
concated = pd.concat([df1, df3])
print (concated)
  animal letter  number
0    NaN      a       1
1    NaN      b       2
0    cat      c       3
1    dog      d       4

# 合并df1和df3,连接方式为inner
concated = pd.concat([df1, df3], join = 'inner')
print (concated)
  letter  number
0      a       1
1      b       2
0      c       3
1      d       4

实例2,按行合并(横向合并):

df1
  letter  number
0      a       1
1      b       2
df4
   animal    name
0    bird   polly
1  monkey  george

# 合并df1和df4
concated = pd.concat([df1, df4], axis=1)
print (concated)
  letter  number  animal    name
0      a       1    bird   polly
1      b       2  monkey  george

4、DataFrame设置索引和还原

(1)设置单索引、复合索引:DataFrame.set_index()

函数原型:
DataFrame.set_index(keys, drop=True, append=False, 
                    inplace=False, verify_integrity=False)

参数介绍:
  keys:列名或者列名的列表
  drop:boolean,默认为True,是否删除列作为新的索引;
  append: boolean,默认为False,是否添加新的列;
  inplace: boolean,默认为False,是否修改原本的DataFrame;
  varify_integrity: boolean,默认为False,检查新索引是否有重复项;

实例:

df
    A   B key1 key2
0  A0  B0   K0   K0
1  A1  B1   K0   K1
2  A2  B2   K1   K0
3  A3  B3   K2   K1

# 单索引
df1=df.set_index('A')
print (df1)
     B key1 key2
A               
A0  B0   K0   K0
A1  B1   K0   K1
A2  B2   K1   K0
A3  B3   K2   K1

# 复合索引
df1=df.set_index(['A','B'])
print (df1)
      key1 key2
A  B           
A0 B0   K0   K0
A1 B1   K0   K1
A2 B2   K1   K0
A3 B3   K2   K1

(2)还原索引,将DataFrame变成整数索引,范围为0 ~ len(df) - 1:DataFrame.reset_index()

函数原型:
DataFrame.reset_index(level=None, drop=False, inplace=False, 
                      col_level=0, col_fill=”)

参数介绍:
  level:int, str, tuple, 或则list, 默认为None,仅从索引中删除给定的级别,默认情况下删除所有级别
  drop:boolean,默认为False,是否删除原有的索引;
  inplace:boolean,默认为False,是否修改原始的DataFrame;
  col_level:int或者str, 默认为0,如果列有多个级别,决定哪个级别的列名被插入,默认情况下是插入第一个级别的。
  col_fill: object, 默认为‘’,如果列有多个级别,决定其它级别的列是如何被命名的。如果为None,则重复索引名称。

 实例:

df
     B key1 key2
A               
A0  B0   K0   K0
A1  B1   K0   K1
A2  B2   K1   K0
A3  B3   K2   K1

# 保留原有索引
df1=df.reset_index()
print (df1)
    A   B key1 key2
0  A0  B0   K0   K0
1  A1  B1   K0   K1
2  A2  B2   K1   K0
3  A3  B3   K2   K1

# 删除原有索引
df2=df.reset_index(drop = True)
print (df2)
    B key1 key2
0  B0   K0   K0
1  B1   K0   K1
2  B2   K1   K0
3  B3   K2   K1

5、去除特定列下面的重复行

函数原型:
  DataFrame.drop_duplicates(subset=None, keep='first', inplace=False)

参数:
  subset:列名或列名的序列,用来指定特定的列,默认所有列
  keep: {‘first’, ‘last’, False}, 默认为‘first’,
     first : 删除重复行,除了第一次出现的行;
     last : 删除重复行,除了最后一次出现的行;
     False :删除所有重复的行;
  inplace:boolean,默认为False,是否修改原DataFrame;

实例:

df
    A   B key1 key2
0  A0  B0   K0   K0
1  A1  B1   K0   K1
2  A2  B2   K1   K0
3  A3  B3   K2   K1

df1 = df.drop_duplicates('key2','first')
print (df1)
    A   B key1 key2
0  A0  B0   K0   K0
1  A1  B1   K0   K1

6、分类变量(categorical variable)转换为“哑变量矩阵”(dummy matrix)或“指标矩阵”(indicator matrix)

  如果DataFrame的某一列中含有k个不同的值,则可以派生出一个k列矩阵或DataFrame(其值全为1和0),这是一种常用于统计建模或机器学习的转换方式。pandas有一个get_dummies()函数可以实现该功能.。实例如下:

df
    A   B key1 key2
0  A0  B0   K0   K0
1  A1  B1   K0   K1
2  A2  B2   K1   K0
3  A3  B3   K2   K1

df2=pd.get_dummies(df['A'])
print (df2)
    A0   A1   A2   A3
0  1.0  0.0  0.0  0.0
1  0.0  1.0  0.0  0.0
2  0.0  0.0  1.0  0.0
3  0.0  0.0  0.0  1.0

df2=pd.get_dummies(df['key1'])
print (df2)
    K0   K1   K2
0  1.0  0.0  0.0
1  1.0  0.0  0.0
2  0.0  1.0  0.0
3  0.0  0.0  1.0

 

  • 0
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python pandas是一个数据分析工具,提供了DataFrame数据结构,它有许多常见的函数可以对数据进行处理和分析。 1. 读取数据:通过read_csv()函数可以将csv格式的文件读取为DataFrame对象,并通过to_csv()函数DataFrame对象保存为csv文件。 2. 选取数据:使用loc()和iloc()函数可以根据标签或索引选取DataFrame中的行和列。例如,df.loc[0]可以选择第一行,df.loc[:, 'A']可以选择'A'列。 3. 描述数据:describe()函数可以提供DataFrame中数值列的基本统计信息,如计数、均值、标准差等。 4. 排序数据:通过sort_values()函数可以根据指定的列或多个列对DataFrame进行排序。 5. 筛选数据:使用条件表达式可以筛选出满足条件的数据,例如df[df['A'] > 0]可以筛选出'A'列大于0的数据。 6. 缺失值处理:fillna()函数可以将DataFrame中的缺失值用指定的值进行填充,dropna()函数可以删除包含缺失值的行或列。 7. 合并数据:通过concat()和merge()函数可以将多个DataFrame对象按指定的方式合并成一个新的DataFrame。 8. 统计计算:DataFrame提供了一些常见的统计计算函数,如sum()、mean()、median()等,可以对指定的列进行计算。 9. 分组操作:使用groupby()函数可以按照指定的列对DataFrame进行分组操作,然后进行聚合计算,如求和、平均值等。 10. 数据透视表:使用pivot_table()函数可以根据指定的行和列对DataFrame进行透视操作,类似于Excel中的数据透视表。 这些函数只是常见的一部分,Python pandas还提供了很多其他强大的函数和特性,可以根据实际需求去探索和应用。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值