1.DataFrame常用属性、函数以及索引方式

1.1DataFrame简介

  DataFrame是一个表格型的数据结构,它含有一组有序的列,每列可以是不同的值类型(数值、字符串、布尔值等)。DataFrame既有行索引也有列索引,它可以被看做由Series组成的字典(共用同一个索引)。DataFrame可以通过类似字典的方式或者.columnname的方式将列获取为一个Series。行也可以通过位置或名称的方式进行获取。

    为不存在的列赋值会创建新列。

    >>> del frame['xxx']  # 删除列

1.2DataFrame常用属性

属性 说明
values DataFrame的值
index 行索引
index.name 行索引的名字
columns 列索引
columns.name 列索引的名字
ix 返回行的DataFrame
ix[[x,y,...], [x,y,...]] 对行重新索引,然后对列重新索引
T frame行列转置
   

1.3DataFrame常用函数

1.3.1函数

说明

DataFrame(dict, columns=dict.index, index=[dict.columnnum])

DataFrame(二维ndarray)

DataFrame(由数组、列表或元组组成的字典)

DataFrame(NumPy的结构化/记录数组)

DataFrame(由Series组成的字典)

DataFrame(由字典组成的字典)

DataFrame(字典或Series的列表)

DataFrame(由列表或元组组成的列表)

DataFrame(DataFrame)

DataFrame(NumPy的MaskedArray)

构建DataFrame

数据矩阵,还可以传入行标和列标

每个序列会变成DataFrame的一列。所有序列的长度必须相同

类似于“由数组组成的字典”

每个Series会成为一列。如果没有显式制定索引,则各Series的索引会被合并成结果的行索引

各内层字典会成为一列。键会被合并成结果的行索引。

各项将会成为DataFrame的一行。索引的并集会成为DataFrame的列标。

类似于二维ndarray

沿用DataFrame

类似于二维ndarray,但掩码结果会变成NA/缺失值

df.reindex([x,y,...], fill_value=NaN, limit)

df.reindex([x,y,...], method=NaN)

df.reindex([x,y,...], columns=[x,y,...],copy=True)

返回一个适应新索引的新对象,将缺失值填充为fill_value,最大填充量为limit

返回适应新索引的新对象,填充方式为method

同时对行和列进行重新索引,默认复制新对象。

df.drop(index, axis=0) 丢弃指定轴上的指定项。
   

1.3.2排序函数

说明

df.sort_index(axis=0, ascending=True)

df.sort_index(by=[a,b,...])

根据索引排序
   

1.3.3汇总统计函数

说明
df.count() 非NaN的数量
df.describe() 一次性产生多个汇总统计

df.min()

df.min()

最小值

最大值

df.idxmax(axis=0, skipna=True)

df.idxmin(axis=0, skipna=True)

返回含有最大值的index的Series

返回含有最小值的index的Series

df.quantile(axis=0) 计算样本的分位数

df.sum(axis=0, skipna=True, level=NaN)

df.mean(axis=0, skipna=True, level=NaN)

df.median(axis=0, skipna=True, level=NaN)

df.mad(axis=0, skipna=True, level=NaN)

df.var(axis=0, skipna=True, level=NaN)

df.std(axis=0, skipna=True, level=NaN)

df.skew(axis=0, skipna=True, level=NaN)

df.kurt(axis=0, skipna=True, level=NaN)

df.cumsum(axis=0, skipna=True, level=NaN)

df.cummin(axis=0, skipna=True, level=NaN)

df.cummax(axis=0, skipna=True, level=NaN)

df.cumprod(axis=0, skipna=True, level=NaN)

df.diff(axis=0)

df.pct_change(axis=0)

返回一个含有求和小计的Series

返回一个含有平均值的Series

返回一个含有算术中位数的Series

返回一个根据平均值计算平均绝对离差的Series

返回一个方差的Series

返回一个标准差的Series

返回样本值的偏度(三阶距)

返回样本值的峰度(四阶距)

返回样本的累计和

返回样本的累计最大值

返回样本的累计最小值

返回样本的累计积

返回样本的一阶差分

返回样本的百分比数变化

   
   

1.3.4计算函数

说明 

df.add(df2, fill_value=NaN, axist=1)

df.sub(df2, fill_value=NaN, axist=1)

df.div(df2, fill_value=NaN, axist=1)

df.mul(df2, fill_value=NaN, axist=1)

元素级相加,对齐时找不到元素默认用fill_value

元素级相减,对齐时找不到元素默认用fill_value

元素级相除,对齐时找不到元素默认用fill_value

元素级相乘,对齐时找不到元素默认用fill_value

df.apply(f, axis=0) 将f函数应用到由各行各列所形成的一维数组上
df.applymap(f) 将f函数应用到各个元素上
df.cumsum(axis=0, skipna=True) 累加,返回累加后的dataframe

1.4DataFrame索引方式

索引方式 说明
df[val] 选取DataFrame的单个列或一组列
df.ix[val] 选取Dataframe的单个行或一组行
df.ix[:,val] 选取单个列或列子集
df.ix[val1,val2] 将一个或多个轴匹配到新索引
reindex方法 将一个或多个轴匹配到新索引
xs方法 根据标签选取单行或者单列,返回一个Series
icol、irow方法 根据整数位置选取单列或单行,并返回一个Series
get_value、set_value 根据行标签和列标签选取单个值

运算:默认情况下,Dataframe和Series之间的算术运算会将Series的索引匹配到的Dataframe的列,沿着列一直向下传播。若索引找不到,则会重新索引产生并集。

2.DataFrame常用属性例程

  1. # -*- coding: utf-8 -*-
  2. """
  3. @author: 蔚蓝的天空Tom
  4. DataFrame是一个表格型的数据结构,它含有一组有序的列,每列可以是不同的值类型(数值、字符串、布尔值等)。
  5. DataFrame既有行索引也有列索引,它可以被看做由Series组成的字典(共用同一个索引)。
  6. DataFrame可以通过类似字典的方式或者.columnname的方式将列获取为一个Series。
  7. 行也可以通过位置或名称的方式进行获取。
  8. DataFrame常用属性
  9. 属性 说明
  10. values DataFrame的值
  11. index 行索引
  12. index.name 行索引的名字
  13. columns 列索引
  14. columns.name 列索引的名字
  15. ix 返回行的DataFrame
  16. ix[[x,y,...], [x,y,...]] 对行重新索引,然后对列重新索引
  17. T frame行列转置
  18. """
  19. import pandas as pd
  20. from pandas import DataFrame
  21. if __name__=='__main__':
  22. data = {'Name':['Tom','Kim','Andy'],
  23. 'Age':[18,16,19],
  24. 'Height':[1.6,1.5,1.7]}
  25. ind = ['No.1', 'No.2', 'No.3']
  26. df = pd.DataFrame(data, index=ind)
  27. # Age Height Name
  28. #No.1 18 1.6 Tom
  29. #No.2 16 1.5 Kim
  30. #No.3 19 1.7 Andy
  31. #DataFram的值
  32. v = df.values #<class 'numpy.ndarray'>
  33. #[[18 1.6 'Tom']
  34. # [16 1.5 'Kim']
  35. # [19 1.7 'Andy']]
  36. #行索引,用户没有自定义行索引index时,返回行索引魔人数值
  37. ind = df.index #<class 'pandas.indexes.base.Index'>
  38. #Index(['No.1', 'No.2', 'No.3'], dtype='object')
  39. #行索引的名字,未设置时获取到None
  40. iname = df.index.name
  41. #None
  42. #行索引的名字,先设置再获取
  43. df.index.name = 'StudentID'
  44. iname = df.index.name
  45. #StudentID
  46. #列索引
  47. col = df.columns #<class 'pandas.indexes.base.Index'>
  48. #Index(['Age', 'Height', 'Name'], dtype='object')
  49. #列索引的名字, 未设置时为None
  50. cname = df.columns.name
  51. #None
  52. #列索引的名字,先设置再获取
  53. df.columns.name = 'StudentInfo'
  54. cname = df.columns.name
  55. #StudentInfo
  56. #ix, 返回行的DataFrame
  57. ret = df.ix[0] #返回第一行数据
  58. #Age 18
  59. #Height 1.6
  60. #Name Tom
  61. #Name: No.1, dtype: object
  62. #ix, 返回行的DataFrame
  63. ret = df.ix[1] #返回第二行数据, <class 'pandas.core.series.Series'>
  64. #Age 16
  65. #Height 1.5
  66. #Name Kim
  67. #Name: No.2, dtype: object
  68. ret = df.ix[-1] #返回最后一行数据
  69. #Age 19
  70. #Height 1.7
  71. #Name Andy
  72. #Name: No.3, dtype: object
  73. #ix[[rowx, rowy,...]] 对行重新索引,相等于DataFrame切片
  74. ret = df.ix[[0,2]]
  75. #StudentInfo Age Height Name
  76. #StudentID
  77. #No.1 18 1.6 Tom
  78. #No.2 16 1.5 Kim
  79. #ix[[rowx, rowy,...], [colx, coly, ...]]
  80. ret = df.ix[[0,2], [0,1]]
  81. #StudentInfo Age Height
  82. #StudentID
  83. #No.1 18 1.6
  84. #No.3 19 1.7
  85. #T frame行列转置
  86. print('转置前:\n', df)
  87. #转置前:
  88. #StudentInfo Age Height Name
  89. #StudentID
  90. #No.1 18 1.6 Tom
  91. #No.2 16 1.5 Kim
  92. #No.3 19 1.7 Andy
  93. print('转置前values:\n', df.values)
  94. #转置前values:
  95. # [[18 1.6 'Tom']
  96. # [16 1.5 'Kim']
  97. # [19 1.7 'Andy']]
  98. dfT = df.T
  99. print('转置后:\n', dfT)
  100. #转置后:
  101. #StudentID No.1 No.2 No.3
  102. #StudentInfo
  103. #Age 18 16 19
  104. #Height 1.6 1.5 1.7
  105. #Name Tom Kim Andy
  106. print('转置后values:\n', dfT.values)
  107. #转置后values:
  108. # [[18 16 19]
  109. # [1.6 1.5 1.7]
  110. # ['Tom' 'Kim' 'Andy']]
  111. print('转置前index.name:\n', df.index.name)
  112. #StudentID
  113. print('转置后index.name:\n', dfT.index.name)
  114. #StudentInfo
  115. print('转置前columns.name:\n', df.columns.name)
  116. #StudentInfo
  117. print('转置后columns.name:\n', dfT.columns.name)
  118. #StudentID

3.DataFrame常用函数DataFrame()/reindex()/drop()

  1. def DataFrame_manual():
  2. '''
  3. DataFrame类型类似于数据库表结构的数据结构,含有行索引和列索引
  4. 可以将DataFrame看成由相同索引的Series组成的Dict类型。
  5. 在其底层是通过二维以及一维的数据块实现
  6. '''
  7. import pandas as pd
  8. from pandas import DataFrame
  9. #1. DataFrame对象的创建
  10. #1.1用包含等长的列表或者是NumPy数组的字典创建DataFrame对象
  11. #建立等长列表的字典类型
  12. data = {'Name':['Tom', 'Kim', 'Andy'],
  13. 'Age':[18, 16, 19],
  14. 'Height':[1.6, 1.5, 1.7]}
  15. #建立DataFrame对象
  16. #使用默认索引[0,1,2,....]
  17. df = pd.DataFrame(data) #默认索引,默认列的顺序
  18. # Age Height Name
  19. # 0 18 1.6 Tom
  20. # 1 16 1.5 Kim
  21. # 2 19 1.7 Andy
  22. #指定列的顺序
  23. df = pd.DataFrame(data, columns=['Name', 'Age', 'Height'])
  24. # Name Age Height
  25. # 0 Tom 18 1.6
  26. # 1 Kim 16 1.5
  27. # 2 Andy 19 1.7
  28. #指定DataFrame的索引
  29. df = pd.DataFrame(data, index=['1st', '2nd', '3th'])
  30. # Age Height Name
  31. # 1st 18 1.6 Tom
  32. # 2nd 16 1.5 Kim
  33. # 3th 19 1.7 Andy
  34. #1.2 用嵌套dict生成DataFrame对象
  35. #用嵌套dict生成DataFrame,外部的dict索引会成为列名,内部的dict索引会成为行名
  36. #生成的DataFrame会根据行索引排序
  37. data = {'Name': {'1st':'Tom', '2nd':'Kim', '3th':'Andy'},
  38. 'Age': {'1st':18, '2nd':16, '3th':19},
  39. 'Height':{'1st':1.6, '2nd':1.5, '3th':1.7}}
  40. df = pd.DataFrame(data) #使用嵌套dict指定的行序列,使用默认的列序列(列名字典排序)
  41. # Age Height Name
  42. # 1st 18 1.6 Tom
  43. # 2nd 16 1.5 Kim
  44. # 3th 19 1.7 Andy
  45. df = pd.DataFrame(data, ['3th', '2nd', '1st']) #指定行的序列
  46. # Age Height Name
  47. # 3th 19 1.7 Andy
  48. # 2nd 16 1.5 Kim
  49. # 1st 18 1.6 Tom
  50. #2访问DataFrame
  51. #从DataFrame中获取一列的结果为一个Series,有两种方法
  52. #2.1字典索引方式获取
  53. data = {'Name':['Tom', 'Kim', 'Andy'],
  54. 'Age':[18, 16, 19],
  55. 'Height':[1.6, 1.5, 1.7]}
  56. df = pd.DataFrame(data, columns=['Name', 'Age', 'Height'], index=['1st', '2nd', '3th'])
  57. # Name Age Height
  58. # 1st Tom 18 1.6
  59. # 2nd Kim 16 1.5
  60. # 3th Andy 19 1.7
  61. s = df['Name']
  62. # 1st Tom
  63. # 2nd Kim
  64. # 3th Andy
  65. # Name: Name, dtype: object
  66. #2.2通过ix获取一行数据
  67. data = {'Name':['Tom', 'Kim', 'Andy'],
  68. 'Age':[18, 16, 19],
  69. 'Height':[1.6, 1.5, 1.7]}
  70. df = pd.DataFrame(data,
  71. columns=['Name', 'Age', 'Height'],
  72. index=['1st', '2nd', '3th'])
  73. s = df.ix['1st'] #获取单行,参数为 行索引值
  74. # Name Tom
  75. # Age 18
  76. # Height 1.6
  77. # Name: 1st, dtype: object
  78. s = df.ix[0] #获取单行,参数 默认数字行索引
  79. # Name Tom
  80. # Age 18
  81. # Height 1.6
  82. # Name: 1st, dtype: object
  83. s = df.ix[['3th', '2nd']]#获取多行
  84. # Name Age Height
  85. # 3th Andy 19 1.7
  86. # 2nd Kim 16 1.5
  87. s = df.ix[range(3)] #通过默认数字行索引获取数据
  88. # Name Age Height
  89. # 1st Tom 18 1.6
  90. # 2nd Kim 16 1.5
  91. # 3th Andy 19 1.7
  92. #2.3获取指定行,指定列的交汇值
  93. ret = df['Name']['1st'] #Tom
  94. ret = df['Name'][0] #Tom
  95. ret = df['Age']['1st'] #18
  96. ret = df['Age'][0] #18
  97. ret = df['Height']['1st']#1.6
  98. ret = df['Height'][0] #1.6
  99. #2.4获取指定列,指定行的交汇值
  100. ret = df.ix['1st']['Name'] #Tom
  101. ret = df.ix[0]['Name'] #Tom
  102. ret = df.ix['1st']['Age'] #18
  103. ret = df.ix[0]['Age'] #18
  104. ret = df.ix['1st']['Height']#1.6
  105. ret = df.ix[0]['Height'] #1.6
  106. #3.修改DataFame对象
  107. #3.1增加列
  108. data = {'Name':['Tom', 'Kim', 'Andy'],
  109. 'Age':[18, 16, 19],
  110. 'Height':[1.6, 1.5, 1.7]}
  111. df = pd.DataFrame(data,
  112. columns=['Name', 'Age', 'Height'],
  113. index=['1st', '2nd', '3th'])
  114. df['Grade'] = 9 #增加一列,年级'Grade',为同一值9年级
  115. # Name Age Height Grade
  116. # 1st Tom 18 1.6 9
  117. # 2nd Kim 16 1.5 9
  118. # 3th Andy 19 1.7 9
  119. #3.2修改一列的值
  120. df['Grade'] = [6,7,7]
  121. # Name Age Height Grade
  122. # 1st Tom 18 1.6 6
  123. # 2nd Kim 16 1.5 7
  124. # 3th Andy 19 1.7 7
  125. #3.3判断Grade是否为7年级
  126. s = pd.Series([False, True, True], index=['1st', '2nd', '3th'])
  127. df['HighGrade'] = s #新增一列'HighGrade',用Series赋值
  128. # Name Age Height Grade HighGrade
  129. # 1st Tom 18 1.6 6 False
  130. # 2nd Kim 16 1.5 7 True
  131. # 3th Andy 19 1.7 7 True
  132. #4.命令DataFrame的行、列
  133. data = {'Name':['Tom', 'Kim', 'Andy'],
  134. 'Age':[18, 16, 19],
  135. 'Height':[1.6, 1.5, 1.7]}
  136. df = pd.DataFrame(data,
  137. columns=['Name', 'Age', 'Height'],
  138. index=['1st', '2nd', '3th'])
  139. df.columns.name = 'Students'
  140. df.index.name = 'ID'
  141. # Students Name Age Height
  142. # ID
  143. # 1st Tom 18 1.6
  144. # 2nd Kim 16 1.5
  145. # 3th Andy 19 1.7

4.DataFrame排序函数

  1. def DataFrame_Sort():
  2. data = {'Name': {'No.1':'Tom', 'No.2':'Kim', 'No.3':'Andy'},
  3. 'Age': {'No.1':18, 'No.2':16, 'No.3':19},
  4. 'Height':{'No.1':1.6, 'No.2':1.5, 'No.3':1.7}}
  5. df = pd.DataFrame(data)
  6. df.index.name = 'ID'
  7. df.columns.name = 'StudentInfo'
  8. #StudentInfo Age Height Name
  9. #ID
  10. #No.1 18 1.6 Tom
  11. #No.2 16 1.5 Kim
  12. #No.3 19 1.7 Andy
  13. #行索引排序,升序
  14. ret = df.sort_index(ascending=True)
  15. #StudentInfo Age Height Name
  16. #ID
  17. #No.1 18 1.6 Tom
  18. #No.2 16 1.5 Kim
  19. #No.3 19 1.7 Andy
  20. #行索引排序,降序
  21. ret = df.sort_index(ascending=False)
  22. #StudentInfo Age Height Name
  23. #ID
  24. #No.3 19 1.7 Andy
  25. #No.2 16 1.5 Kim
  26. #No.1 18 1.6 Tom
  27. #数据排序,按照指定列排序,降序
  28. ret = df.sort_values(by='Age', ascending=True) #按照Age列降序排序
  29. #StudentInfo Age Height Name
  30. #ID
  31. #No.2 16 1.5 Kim
  32. #No.1 18 1.6 Tom
  33. #No.3 19 1.7 Andy
  34. #数据排序,按照指定列排序,升序
  35. ret = df.sort_values(by='Age', ascending=False)
  36. #StudentInfo Age Height Name
  37. #ID
  38. #No.3 19 1.7 Andy
  39. #No.1 18 1.6 Tom
  40. #No.2 16 1.5 Kim

5.DataFrame汇总统计函数

  1. # -*- coding: utf-8 -*-
  2. """
  3. @author: 蔚蓝的天空Tom
  4. Aim:DataFrame的汇总统计功能函数
  5. df.count() 非NaN的数量
  6. df.describe() 一次性产生多个汇总统计
  7. df.min() 最小值
  8. df.min() 最大值
  9. df.idxmax(axis=0, skipna=True) 返回含有最大值的index的Series
  10. df.idxmin(axis=0, skipna=True) 返回含有最小值的index的Series
  11. df.quantile(axis=0) 计算样本的分位数
  12. df.sum(axis=0, skipna=True, level=NaN) 返回一个含有求和小计的Series
  13. df.mean(axis=0, skipna=True, level=NaN) 返回一个含有平均值的Series
  14. df.median(axis=0, skipna=True, level=NaN) 返回一个含有算术中位数的Series
  15. df.mad(axis=0, skipna=True, level=NaN) 返回一个根据平均值计算平均绝对离差的Series
  16. df.var(axis=0, skipna=True, level=NaN) 返回一个方差的Series
  17. df.std(axis=0, skipna=True, level=NaN) 返回一个标准差的Series
  18. df.skew(axis=0, skipna=True, level=NaN) 返回样本值的偏度(三阶距)
  19. df.kurt(axis=0, skipna=True, level=NaN) 返回样本值的峰度(四阶距)
  20. df.cumsum(axis=0, skipna=True, level=NaN) 返回样本的累计和
  21. df.cummin(axis=0, skipna=True, level=NaN) 返回样本的累计最大值
  22. df.cummax(axis=0, skipna=True, level=NaN) 返回样本的累计最小值
  23. df.cumprod(axis=0, skipna=True, level=NaN) 返回样本的累计积
  24. df.diff(axis=0) 返回样本的一阶差分
  25. df.pct_change(axis=0) 返回样本的百分比数变化
  26. """
  27. import pandas as pd
  28. from pandas import DataFrame
  29. if __name__=='__main__':
  30. data = {'Name':['Tom', 'Kim', 'Andy'],
  31. 'Age':[18, 16, 19],
  32. 'Height':[1.6, 1.5, 1.7]}
  33. ind = ['No.1', 'No.2', 'No.3']
  34. df = pd.DataFrame(data, index=ind)
  35. df.index.name = 'ID'
  36. df.columns.name = 'StudentInfo'
  37. #StudentInfo Age Height Name
  38. #ID
  39. #No.1 18 1.6 Tom
  40. #No.2 16 1.5 Kim
  41. #No.3 19 1.7 Andy
  42. #df.count() 非NaN的数量
  43. cnt = df.count()
  44. #StudentInfo
  45. #Age 3
  46. #Height 3
  47. #Name 3
  48. #dtype: int64
  49. #df.describe()一次性产生多个汇总统计(包括count, mean, std, min, max等)
  50. ret = df.describe() #<class 'pandas.core.frame.DataFrame'>
  51. #StudentInfo Age Height
  52. #count 3.000000 3.00
  53. #mean 17.666667 1.60
  54. #std 1.527525 0.10
  55. #min 16.000000 1.50
  56. #25% 17.000000 1.55
  57. #50% 18.000000 1.60
  58. #75% 18.500000 1.65
  59. #max 19.000000 1.70
  60. #df.min() 最小值,每列的最小数值
  61. ret = df.min()
  62. #StudentInfo
  63. #Age 16
  64. #Height 1.5
  65. #Name Andy
  66. #dtype: object
  67. #df.min() 最大值,每列的最大数值
  68. ret = df.max()
  69. #StudentInfo
  70. #Age 19
  71. #Height 1.7
  72. #Name Tom
  73. #dtype: object
  74. #df.idxmax(axis=0, skipna=True) 返回含有最大值的index的Series
  75. data = {'Age':[18,16,19],
  76. 'Height':[1.6, 1.5, 1.7],
  77. 'Math':[60, 70, 100],
  78. 'English':[98, 68, 69],
  79. 'Chinese':[50, 99, 70]}
  80. ind = ['No.1', 'No.2', 'No.3']
  81. df = pd.DataFrame(data, index=ind)
  82. df.index.name = 'ID'
  83. df.columns.name = 'Student'
  84. #Student Age Chinese English Height Math
  85. #ID
  86. #No.1 18 50 98 1.6 60
  87. #No.2 16 99 68 1.5 70
  88. #No.3 19 70 69 1.7 100
  89. #df.idxmin(axis=0, skipna=True) 返回含有最小值的index的Series
  90. ret = df.idxmax(axis = 0) #<class 'pandas.core.series.Series'>
  91. #Student
  92. #Age No.3
  93. #Chinese No.2
  94. #English No.1
  95. #Height No.3
  96. #Math No.3
  97. #dtype: object
  98. #每行最大数据所在列名
  99. ret = df.idxmax(axis = 1) #<class 'pandas.core.series.Series'>
  100. #ID
  101. #No.1 English
  102. #No.2 Chinese
  103. #No.3 Math
  104. #dtype: object
  105. #df.quantile(axis=0) 计算样本的分位数(有二分位数,四分位数等)
  106. ret = df.quantile(axis = 0) #每列样本的中位数
  107. #Student
  108. #Age 18.0
  109. #Chinese 70.0
  110. #English 69.0
  111. #Height 1.6
  112. #Math 70.0
  113. #dtype: float64
  114. #df.sum(axis=0, skipna=True, level=NaN) 返回一个含有求和小计的Series
  115. ret = df.sum(axis=0) #每列样本的总和
  116. #Student
  117. #Age 53.0
  118. #Chinese 219.0
  119. #English 235.0
  120. #Height 4.8
  121. #Math 230.0
  122. #dtype: float64
  123. ret = df.sum(axis=1) #每行数据的总和,从此样本看没有任何意义
  124. #ID
  125. #No.1 227.6
  126. #No.2 254.5
  127. #No.3 259.7
  128. #dtype: float64
  129. #df.mean(axis=0, skipna=True, level=NaN) 返回一个含有平均值的Series
  130. ret = df.mean(axis=0) #每列样本的平均值
  131. #Student
  132. #Age 17.666667
  133. #Chinese 73.000000
  134. #English 78.333333
  135. #Height 1.600000
  136. #Math 76.666667
  137. #dtype: float64
  138. ret = df.mean(axis=1) #每行数据的平均值,以此样本看没有任何意义
  139. #ID
  140. #No.1 45.52
  141. #No.2 50.90
  142. #No.3 51.94
  143. #dtype: float64
  144. #df.median(axis=0, skipna=True, level=NaN) 返回一个含有算术中位数的Series
  145. ret = df.median(axis=0) #每列样本的中位数
  146. #Student
  147. #Age 18.0
  148. #Chinese 70.0
  149. #English 69.0
  150. #Height 1.6
  151. #Math 70.0
  152. #dtype: float64
  153. ret = df.median(axis=1) #每行数据的中位数
  154. #ID
  155. #No.1 50.0
  156. #No.2 68.0
  157. #No.3 69.0
  158. #dtype: float64
  159. #df.mad(axis=0, skipna=True, level=NaN) 返回一个根据平均值计算平均绝对离差的Series
  160. #绝对离差=单项数值与平均值之差的绝对值
  161. #Student Age Chinese English Height Math
  162. #ID
  163. #No.1 18 50 98 1.6 60
  164. #No.2 16 99 68 1.5 70
  165. #No.3 19 70 69 1.7 100
  166. ret = df.mad(axis=0) #逐列求值
  167. #Student
  168. #Age 1.111111
  169. #Chinese 17.333333
  170. #English 13.111111
  171. #Height 0.066667
  172. #Math 15.555556
  173. #dtype: float64
  174. ret = df.mad(axis=1) #逐行求值
  175. #ID
  176. #No.1 28.576
  177. #No.2 33.720
  178. #No.3 33.272
  179. #dtype: float64
  180. #df.var(axis=0, skipna=True, level=NaN) 返回一个方差的Series
  181. ret = df.var(axis=0) #逐列操作求方差
  182. #Student
  183. #Age 2.333333
  184. #Chinese 607.000000
  185. #English 290.333333
  186. #Height 0.010000
  187. #Math 433.333333
  188. #dtype: float64
  189. ret = df.var(axis=1) #逐行操作求方差
  190. #ID
  191. #No.1 1417.552
  192. #No.2 1657.300
  193. #No.3 1634.018
  194. #dtype: float64
  195. #df.std(axis=0, skipna=True, level=NaN) 返回一个标准差的Series
  196. ret = df.std(axis=0) #逐列求标准差
  197. #Student
  198. #Age 1.527525
  199. #Chinese 24.637370
  200. #English 17.039171
  201. #Height 0.100000
  202. #Math 20.816660
  203. #dtype: float64
  204. ret = df.std(axis=1) #逐行求标准差
  205. #ID
  206. #No.1 37.650392
  207. #No.2 40.709950
  208. #No.3 40.422989
  209. #dtype: float64
  210. #df.skew(axis=0, skipna=True, level=NaN) 返回样本值的偏度(三阶距)
  211. ret = df.skew(axis=0) #逐列求样本值的偏度(三阶矩)
  212. #Student
  213. #Age -0.935220
  214. #Chinese 0.539824
  215. #English 1.725342
  216. #Height 0.000000
  217. #Math 1.293343
  218. #dtype: float64
  219. ret = df.skew(axis=1) #逐行求样本值的偏度(三阶矩)
  220. #ID
  221. #No.1 0.328682
  222. #No.2 -0.245853
  223. #No.3 -0.256661
  224. #dtype: float64
  225. #df.kurt(axis=0, skipna=True, level=NaN) 返回样本值的峰度(四阶距)
  226. ret = df.kurt(axis=0) #逐列求样本值的峰度(四阶距)
  227. #Student
  228. #Age NaN
  229. #Chinese NaN
  230. #English NaN
  231. #Height NaN
  232. #Math NaN
  233. #dtype: float64
  234. ret = df.kurt(axis=1) #逐行求样本值的峰度(四阶距)
  235. #ID
  236. #No.1 -0.582437
  237. #No.2 -2.079006
  238. #No.3 -1.879115
  239. #dtype: float64
  240. #df.cumsum(axis=0, skipna=True, level=NaN) 返回样本的累计和
  241. ret = df.cumsum(axis=0) #逐列求累积和
  242. #Student Age Chinese English Height Math
  243. #ID
  244. #No.1 18.0 50.0 98.0 1.6 60.0
  245. #No.2 34.0 149.0 166.0 3.1 130.0
  246. #No.3 53.0 219.0 235.0 4.8 230.0
  247. ret = df.cumsum(axis=1)#逐行求累积和
  248. #Student Age Chinese English Height Math
  249. #ID
  250. #No.1 18.0 68.0 166.0 167.6 227.6
  251. #No.2 16.0 115.0 183.0 184.5 254.5
  252. #No.3 19.0 89.0 158.0 159.7 259.7
  253. #df.cummin(axis=0, skipna=True, level=NaN) 返回样本的累计最小值
  254. ret = df.cummin(axis=0) #逐列求累计最小值
  255. #Student Age Chinese English Height Math
  256. #ID
  257. #No.1 18.0 50.0 98.0 1.6 60.0
  258. #No.2 16.0 50.0 68.0 1.5 60.0
  259. #No.3 16.0 50.0 68.0 1.5 60.0
  260. ret = df.cummin(axis=1) #逐行求累计最小值
  261. #Student Age Chinese English Height Math
  262. #ID
  263. #No.1 18.0 18.0 18.0 1.6 1.6
  264. #No.2 16.0 16.0 16.0 1.5 1.5
  265. #No.3 19.0 19.0 19.0 1.7 1.7
  266. #df.cummax(axis=0, skipna=True, level=NaN) 返回样本的累计最大值
  267. ret = df.cummax(axis=0) #逐列求累计最大值
  268. #Student Age Chinese English Height Math
  269. #ID
  270. #No.1 18.0 50.0 98.0 1.6 60.0
  271. #No.2 18.0 99.0 98.0 1.6 70.0
  272. #No.3 19.0 99.0 98.0 1.7 100.0
  273. ret = df.cummax(axis=1) #逐行求累计最大值
  274. #Student Age Chinese English Height Math
  275. #ID
  276. #No.1 18.0 50.0 98.0 98.0 98.0
  277. #No.2 16.0 99.0 99.0 99.0 99.0
  278. #No.3 19.0 70.0 70.0 70.0 100.0
  279. #df.cumprod(axis=0, skipna=True, level=NaN) 返回样本的累计积
  280. ret = df.cumprod(axis=0) #逐列求累计积
  281. #Student Age Chinese English Height Math
  282. #ID
  283. #No.1 18.0 50.0 98.0 1.60 60.0
  284. #No.2 288.0 4950.0 6664.0 2.40 4200.0
  285. #No.3 5472.0 346500.0 459816.0 4.08 420000.0
  286. ret = df.cumprod(axis=1) #逐行求累计积
  287. #Student Age Chinese English Height Math
  288. #ID
  289. #No.1 18.0 900.0 88200.0 141120.0 8467200.0
  290. #No.2 16.0 1584.0 107712.0 161568.0 11309760.0
  291. #No.3 19.0 1330.0 91770.0 156009.0 15600900.0
  292. #df.diff(axis=0) 返回样本的一阶差分
  293. ret = df.diff(axis=0) #逐列求一阶差分
  294. #Student Age Chinese English Height Math
  295. #ID
  296. #No.1 NaN NaN NaN NaN NaN
  297. #No.2 -2.0 49.0 -30.0 -0.1 10.0
  298. #No.3 3.0 -29.0 1.0 0.2 30.0
  299. ret = df.diff(axis=1) #逐行求一阶差分
  300. #<class 'pandas.core.frame.DataFrame'>
  301. #Student Age Chinese English Height Math
  302. #ID
  303. #No.1 NaN 32.0 48.0 NaN -38.0
  304. #No.2 NaN 83.0 -31.0 NaN 2.0
  305. #No.3 NaN 51.0 -1.0 NaN 31.0
  306. #df.pct_change(axis=0) 返回样本的百分比数变化
  307. ret =df.pct_change(axis=0) #逐列求百分比数变化
  308. #Student Age Chinese English Height Math
  309. #ID
  310. #No.1 NaN NaN NaN NaN NaN
  311. #No.2 -0.111111 0.980000 -0.306122 -0.062500 0.166667
  312. #No.3 0.187500 -0.292929 0.014706 0.133333 0.428571
  313. ret = df.pct_change(axis=1) #逐行求百分比数变化
  314. #Student Age Chinese English Height Math
  315. #ID
  316. #No.1 NaN 1.777778 0.960000 -0.983673 36.500000
  317. #No.2 NaN 5.187500 -0.313131 -0.977941 45.666667
  318. #No.3 NaN 2.684211 -0.014286 -0.975362 57.823529

6.DataFrame计算函数

  1. # -*- coding: utf-8 -*-
  2. """
  3. @author: 蔚蓝的天空Tom
  4. Aim:实现DataFrame的计算函数的示例
  5. df.add(df2, fill_value=NaN, axist=1) 元素级相加,对齐时找不到元素默认用fill_value
  6. df.sub(df2, fill_value=NaN, axist=1) 元素级相减,对齐时找不到元素默认用fill_value
  7. df.div(df2, fill_value=NaN, axist=1) 元素级相除,对齐时找不到元素默认用fill_value
  8. df.mul(df2, fill_value=NaN, axist=1) 元素级相乘,对齐时找不到元素默认用fill_value
  9. df.apply(f, axis=0) 将f函数应用到由各行各列所形成的一维数组上
  10. df.applymap(f) 将f函数应用到各个元素上
  11. df.cumsum(axis=0, skipna=True) 累加,返回累加后的dataframe
  12. """
  13. import pandas as pd
  14. from pandas import DataFrame
  15. if __name__=='__main__':
  16. data = {'Math':[2, 4, 6],
  17. 'English':[4, 8, 12]}
  18. ind = ['No.1', 'No.2', 'No.3']
  19. df1 = pd.DataFrame(data, index=ind)
  20. df1.index.name = 'ID'
  21. df1.columns.name = 'Student'
  22. #Student English Math
  23. #ID
  24. #No.1 4 2
  25. #No.2 8 4
  26. #No.3 12 6
  27. data = {'Math':[1,2,3],
  28. 'English':[2,4,6]}
  29. ind = ['No.1', 'No.2', 'No.3']
  30. df2 = pd.DataFrame(data, index=ind)
  31. df2.index.name = 'ID'
  32. df2.columns.name = 'Student'
  33. #Student English Math
  34. #ID
  35. #No.1 2 1
  36. #No.2 4 2
  37. #No.3 6 3
  38. #df.add(df2, fill_value=NaN, axist=1) 元素级相加,对齐时找不到元素默认用fill_value
  39. ret = df1.add(df2) #对应元素相加
  40. #Student English Math
  41. #ID
  42. #No.1 6 3
  43. #No.2 12 6
  44. #No.3 18 9
  45. #df.sub(df2, fill_value=NaN, axist=1) 元素级相减,对齐时找不到元素默认用fill_value
  46. ret = df1.sub(df2) #对应元素相减
  47. #Student English Math
  48. #ID
  49. #No.1 2 1
  50. #No.2 4 2
  51. #No.3 6 3
  52. #df.div(df2, fill_value=NaN, axist=1) 元素级相除,对齐时找不到元素默认用fill_value
  53. ret = df1.div(df2) #对应元素相除
  54. #Student English Math
  55. #ID
  56. #No.1 2.0 2.0
  57. #No.2 2.0 2.0
  58. #No.3 2.0 2.0
  59. #df.mul(df2, fill_value=NaN, axist=1) 元素级相乘,对齐时找不到元素默认用fill_value
  60. ret = df1.mul(df2) #对应元素相乘
  61. #Student English Math
  62. #ID
  63. #No.1 8 2
  64. #No.2 32 8
  65. #No.3 72 18
  66. #df.apply(f, axis=0) 将f函数应用到由各行各列所形成的一维数组上
  67. #Student English Math
  68. #ID
  69. #No.1 4 2
  70. #No.2 8 4
  71. #No.3 12 6
  72. import numpy as np
  73. ret = df1.apply(np.square) #对每个元素进行开平方np.squre
  74. #Student English Math
  75. #ID
  76. #No.1 16 4
  77. #No.2 64 16
  78. #No.3 144 36
  79. #df.applymap(f) 将f函数应用到各个元素上
  80. ret = df1.applymap(np.square)
  81. #Student English Math
  82. #ID
  83. #No.1 16 4
  84. #No.2 64 16
  85. #No.3 144 36
  86. #df.cumsum(axis=0, skipna=True) 累加,返回累加后的dataframe
  87. #Student English Math
  88. #ID
  89. #No.1 4 2
  90. #No.2 8 4
  91. #No.3 12 6
  92. ret = df1.cumsum(axis=0) #对每列内的元素,进行累加
  93. #Student English Math
  94. #ID
  95. #No.1 4 2
  96. #No.2 12 6
  97. #No.3 24 12
  98. ret = df1.cumsum(axis=1) #对每行内的元素,进行累加
  99. #Student English Math
  100. #ID
  101. #No.1 4 6
  102. #No.2 8 12
  103. #No.3 12 18

7.DataFrame常用索引方式例程

  1. # -*- coding: utf-8 -*-
  2. """
  3. @author: 蔚蓝的天空Tom
  4. Aim:完成DataFrame的索引方式的示例----df[], df.ix[], df.reindex(), df.xs(), df.icol()等
  5. 索引方式 说明
  6. df[val] 选取DataFrame的单个列或一组列
  7. df.ix[val] 选取Dataframe的单个行或一组行
  8. df.ix[:,val] 选取单个列或列子集
  9. df.ix[val1,val2] 将一个或多个轴匹配到新索引
  10. reindex方法 将一个或多个轴匹配到新索引
  11. xs方法 根据标签选取单行或者单列,返回一个Series
  12. icol、irow方法 根据整数位置选取单列或单行,并返回一个Series
  13. get_value、set_value 根据行标签和列标签选取单个值
  14. """
  15. import pandas as pd
  16. from pandas import DataFrame
  17. if __name__=='__main__':
  18. data = {'Name':['Tom', 'Kim', 'Andy'],
  19. 'Age':[18, 16, 19],
  20. 'Math':[95, 98, 96]}
  21. ind = ['No.1', 'No.2', 'No.3']
  22. df = pd.DataFrame(data, index=ind, columns=['Name', 'Age', 'Math'])
  23. df.index.name = 'ID'
  24. df.columns.name = 'Student'
  25. #Student Name Age Math
  26. #ID
  27. #No.1 Tom 18 95
  28. #No.2 Kim 16 98
  29. #No.3 Andy 19 96
  30. #选取DataFrame的单个列
  31. ret = df[[0]] #df的第1列
  32. #Student Name
  33. #ID
  34. #No.1 Tom
  35. #No.2 Kim
  36. #No.3 Andy
  37. ret = df[[-1]] #df的最后一列
  38. #Student Math
  39. #ID
  40. #No.1 95
  41. #No.2 98
  42. #No.3 96
  43. ret = df[[-1, 0]] #df的最后一列和第一列
  44. #Student Math Name
  45. #ID
  46. #No.1 95 Tom
  47. #No.2 98 Kim
  48. #No.3 96 Andy
  49. #df.ix[val] 选取Dataframe的单个行或一组行
  50. ret = df.ix[[0]] #df的第一行
  51. #Student Name Age Math
  52. #ID
  53. #No.1 Tom 18 95
  54. ret = df.ix[[-1]] #df的最后一行
  55. #Student Name Age Math
  56. #ID
  57. #No.3 Andy 19 96
  58. ret = df.ix[[-1,0]] #df的最后一行和第一行
  59. #Student Name Age Math
  60. #ID
  61. #No.3 Andy 19 96
  62. #No.1 Tom 18 95
  63. #df.ix[:,val] 选取单个列或列子集
  64. ret = df.ix[0:2, [0]] #第一列中从0到1序号的列子集
  65. #Student Name
  66. #ID
  67. #No.1 Tom
  68. #No.2 Kim
  69. ret = df.ix[:-1, [0]] #第一列中不包含最后一个元素的列子集
  70. #Student Name
  71. #ID
  72. #No.1 Tom
  73. #No.2 Kim
  74. #df.ix[val1,val2] 将一个或多个轴匹配到新索引
  75. ret = df.ix[[0], [0]] #求第一行第一列元素
  76. #Student Name
  77. #ID
  78. #No.1 Tom
  79. ret = df.ix[[0], [1]] #求第一行第二列元素
  80. #Student Age
  81. #ID
  82. #No.1 18
  83. ret = df.ix[[1], [0]] #求第2行第一列元素
  84. #Student Name
  85. #ID
  86. #No.2 Kim

df.reindex()+df.xs()+df.iloc[] + df.get_value() + df.get_values() + df.set_value()

  1. import pandas as pd
  2. from pandas import DataFrame
  3. if __name__=='__main__':
  4. data = {'Name':['Tom', 'Kim', 'Andy'],
  5. 'Age':[18, 16, 19],
  6. 'Height':[1.7, 1.5, 1.6]}
  7. ind = ['No.1', 'No.2', 'No.3']
  8. df = pd.DataFrame(data, index=ind, columns=['Name', 'Age', 'Height'])
  9. df.index.name = 'ID'
  10. df.columns.name = 'Student'
  11. #Student Name Age Height
  12. #ID
  13. #No.1 Tom 18 1.7
  14. #No.2 Kim 16 1.5
  15. #No.3 Andy 19 1.6
  16. #reindex方法 将一个或多个轴匹配到新索引
  17. ret = df.reindex(index=['No.3', 'No.2', 'No.1']) #按照指定的行索引显示
  18. #Student Name Age Height
  19. #ID
  20. #No.3 Andy 19 1.6
  21. #No.2 Kim 16 1.5
  22. #No.1 Tom 18 1.7
  23. ret = df.reindex(index=['No.3', 'No.2', 'No.1'], columns=['Name', 'Age'])
  24. #Student Name Age
  25. #ID
  26. #No.3 Andy 19.0
  27. #No.2 Kim 16.0
  28. #No. NaN NaN
  29. ret = df.reindex(index=['No.1'], columns=['Name', 'Age'])
  30. #Student Name Age
  31. #ID
  32. #No.1 Tom 18
  33. ret = df.reindex(index=['No.1'], columns=['Name'])
  34. #Student Name
  35. #ID
  36. #No.1 Tom
  37. #xs方法 根据标签选取单行或者单列,返回一个Series
  38. ret = df.xs(key='No.1', axis=0)#获取由key指定的行No.1,必须设置axis=0
  39. #Student
  40. #Name Tom
  41. #Age 18
  42. #Height 1.7
  43. #Name: No.1, dtype: object
  44. ret = df.xs(key='Name', axis=1) #获取由key指定的列Name,必须设置axis=1
  45. #ID
  46. #No.1 Tom
  47. #No.2 Kim
  48. #4No.3 Andy
  49. #Name: Name, dtype: object
  50. ret = df.xs(key='Age', axis=1) #获取由key指定的列Age,必须设置axis=1
  51. #ID
  52. #No.1 18

【pandas-汇总3】DataFrame常用属性、函数以及索引方式相关推荐

  1. dataframe两个表合并_Part25:Pandas基础(Series,DataFrame类的创建、索引、切片、算术方法)...

    一.为什么学习pandas numpy已经可以帮助我们进行数据的处理了,那么学习pandas的目的是什么呢? numpy能够帮助我们处理的是数值型的数据,当然在数据分析中除了数值型的数据还有好多其他类 ...

  2. CSS入门(CSS常用属性----字体、对齐方式、display属性、浮动)

    CSS常用属性设置 3.字体 设置字体 font-family ①当font-family的属性值包含空格或特殊字符时,需要将font-family的属性值用引号括起来. ②font-family有& ...

  3. 数据分析(Numpy,Pandas,Matplotlib)常用API

    目录 Numpy Pandas Series DataFrame Matplotlib Series和Dataframe的画图 seaborn Scipy​​​​​​​ Numpy: np.array ...

  4. python pandas包,Python的常用包pandas,numpy

    Pandas 1.DataFrame 和 Series 的介绍import pandas as pd    #导入pandas 包 array = [[1,2,3],[3,4,5]]   #创建列表 ...

  5. dataframe常用操作_Pandas模块基础及常用方法

    Pandas是基于Numpy的数据处理与分析模块.包含两个最重要的基本类型:Series和DataFrame.其中Series类似numpy的一维数组,DataFrame类似二维数组,但可存储不同类型 ...

  6. pandas基础(part2)--DataFrame

    学习笔记,这个笔记以例子为主. 开发工具:Spyder 文章目录 数据框DateFrame 数据结构操作(举例) 列访问 列添加 列删除 行访问 行添加 行删除 修改DataFrame中的数据 Dat ...

  7. python dataframe索引转成列_Pandas之DataFrame对象的列和索引之间的转化

    约定: import pandas as pd DataFrame对象的列和索引之间的转化 我们常常需要将DataFrame对象中的某列或某几列作为索引,或者将索引转化为对象的列.pandas提供了s ...

  8. Pandas中DataFrame的属性、方法、常用操作以及使用示例

    前言 系列文章目录 [Python]目录 视频及资料和课件 链接:https://pan.baidu.com/s/1LCv_qyWslwB-MYw56fjbDg?pwd=1234 提取码:1234 文 ...

  9. [Pandas] 查看DataFrame的常用属性

    导入数据 import pandas as pddf = pd.DataFrame([['L123','A',0,123],['L456','A',1,456],['L437','C',0,789], ...

最新文章

  1. Android中Intent和Intent过滤器详解
  2. 沉降观测曲线图 沉降观测汇总_这些沉降观测要求,工程人必须掌握!
  3. Java基础学习总结(162)——如何保证线程安全?
  4. centos 文件夹网络连接_CentOS的网络配置的命令详解
  5. Ext使用中问题总结
  6. linux设置程序开机自启动
  7. java实现人脸识别(附源码)
  8. 荣耀9换从服务器获取安装包信息失败,华为荣耀9解锁BootLoader教程 荣耀9获取解锁码进行解锁...
  9. 八个程序员常用的接单平台推荐
  10. 计算机论文读书报告怎么写,论文读书报告范文(共6篇).doc
  11. windows 内网域电脑无法ntp时间同步
  12. 人工智能基础入门清单(计算机视觉、强化学习方向/领域)
  13. 华为Mate30系列手机提前发布为哪般?
  14. 【算法图解】第七章:7.5(狄克斯特拉算法优化版)
  15. AWD线下攻防平台搭建
  16. 【数学】扩展卢卡斯定理
  17. 领跑AIoT场景落地 OFweek智慧家庭高峰论坛圆满落幕!
  18. anaconda安装rdkit安装指南
  19. setTimeout和for循环
  20. 三次样条曲线CubicSpline

热门文章

  1. 蓝桥杯python算法提高真题——幸运顾客
  2. 网络媒体十八种赢利模式
  3. 安装时间大于30秒_get朋友圈超长视频模版, 点亮朋友圈30秒“带货神器”
  4. php取模,php数组取模
  5. three.js天空盒贴地解决方案
  6. 【在Kotlin中创建生日祝福语】
  7. pytorch 查找指定元素的索引
  8. 职业饱和逼到风暴中央的程序员们该如何逆势而上?想稳定不掉队还是得拼实力!
  9. 在Excel中利用宏定义实现MD5加密和批量加密
  10. 华为麒麟980内核照