Series

基本介绍

  • Series是一种类似于一维数组的对象,由一组数据(各种Numpy数据类型)以及一组与之对应的索引(数据标签)组成
  • 由数据和索引组成,索引(index)在左,数据(values)在右,索引是自动创建的

    创建Series

  • 语法格式:pandas.Series( data, index, dtype, name, copy)

  • 参数说明
    • data:一组数据(ndarray类型)
    • index:索引标签,如果不指定,默认从0开始
    • dtype:数据类型,默认会自己判断
    • name:设置名称
    • copy:拷贝数据,默认为False

      通过列表创建

      ```python var1 = pd.Series(range(100, 103), name=’hhhh’) print(var1.head(2)) ‘’’ 0 100 1 101 Name: hhhh, dtype: int64 ‘’’ print(var1[0]) # 100 print(var1.index) # RangeIndex(start=0, stop=3, step=1) print(var1.values) # [100 101 102]

var2 = pd.Series([‘Alan’, ‘Bob’, ‘Cindy’], index=[‘x’, ‘y’, ‘z’]) print(var2) ‘’’ x Alan y Bob z Cindy dtype: object ‘’’ print(var2[‘x’]) # Alan

  1. <a name="rcV9o"></a>
  2. #### 通过字典创建
  3. ```python
  4. var1 = pd.Series({'x': "Google", 'y': "Runoob", 'z': "Wiki"})
  5. print(var1)
  6. '''
  7. x Google
  8. y Runoob
  9. z Wiki
  10. dtype: object
  11. '''
  12. ---------------------------------------------------------
  13. var2 = pd.Series({'x': "Google", 'y': "Runoob", 'z': "Wiki"}, index=['x', 'z'])
  14. print(var2)
  15. '''
  16. x Google
  17. z Wiki
  18. dtype: object
  19. '''

DataFrame

基本介绍

DataFrame是一个表格型的数据结构,它含有一组有序的列,每列可以是不同类型的值。DataFrame既有行索引也有列索引,它可以看做是由Series组成的字典(共用同一个索引),数据是以二维结构存放的
image.png

创建DataFrame

  • 语法格式:pandas.DataFrame( data, index, columns, dtype, copy)
  • 参数说明
    • data:一组数据(ndarray、series、map、list、dict等类型)
    • index:索引值,也可以称为行标签,默认为RangeIndex(0, 1, 2, …, n)
    • columns:列标签,默认为RangeIndex(0, 1, 2, …, n)
    • dtype:数据类型
    • copy:拷贝数据,默认为False

      通过列表创建

      ```python print(pd.DataFrame(np.arange(6).reshape(2, 3))) ‘’’ 0 1 2 0 0 1 2 1 3 4 5 ‘’’

data = [[‘Google’], [‘Runoob’, 12], [‘Wiki’, 13]] print(pd.DataFrame(data, columns=[‘Site’, ‘Age’], dtype=float))

按行创建,没有对应部分的数据为NaN

‘’’ Site Age 0 Google NaN 1 Runoob 12.0 2 Wiki 13.0 ‘’’

  1. <a name="spm7c"></a>
  2. #### 通过字典创建
  3. ```python
  4. data = [{'a': 1, 'b': 2}, {'a': 5, 'b': 10, 'c': 20}]
  5. print(pd.DataFrame(data))
  6. # 按行创建,没有对应部分的数据为NaN
  7. '''
  8. a b c
  9. 0 1 2 NaN
  10. 1 5 10 20.0
  11. '''

通过ndarray创建

按列创建,每列的长度必须相同

  1. data = {
  2. 'calories': [420, 380, 390],
  3. 'duration': [50, 40, 45]
  4. }
  5. print(pd.DataFrame(data, index=['day1', 'day2', 'day3']))
  6. '''
  7. calories duration
  8. day1 420 50
  9. day2 380 40
  10. day3 390 45
  11. '''
  12. ---------------------------------------------------------
  13. data = {'A': 1,
  14. 'B': pd.Timestamp('20220709'),
  15. 'C': pd.Series(1, index=list(range(4)), dtype='float32'),
  16. 'D': np.array([1, 2, 3, 4], dtype='int32'),
  17. 'E': ["Python", "Java", "C++", "C"],
  18. 'F': 'program'}
  19. print(pd.DataFrame(data))
  20. '''
  21. A B C D E F
  22. 0 1 2022-07-09 1.0 1 Python program
  23. 1 1 2022-07-09 1.0 2 Java program
  24. 2 1 2022-07-09 1.0 3 C++ program
  25. 3 1 2022-07-09 1.0 4 C program
  26. '''

关于整列的简单操作

  1. data = {
  2. 'calories': [420, 380, 390],
  3. 'duration': [50, 40, 45]
  4. }
  5. df = pd.DataFrame(data, index=['day1', 'day2', 'day3'])
  6. print(df)
  7. '''
  8. calories duration
  9. day1 420 50
  10. day2 380 40
  11. day3 390 45
  12. '''
  13. ---------------------------------------------------------
  14. # 操作一:通过列索引获取整列数据
  15. print(df['calories']) # 等价于print(df.calories)
  16. '''
  17. day1 420
  18. day2 380
  19. day3 390
  20. Name: calories, dtype: int64
  21. '''
  22. print(type(df['calories'])) # <class 'pandas.core.series.Series'>
  23. ---------------------------------------------------------
  24. # 操作二:增加整列数据
  25. df['A'] = df['calories'] + 100
  26. print(df)
  27. '''
  28. calories duration A
  29. day1 420 50 520
  30. day2 380 40 480
  31. day3 390 45 490
  32. '''
  33. ---------------------------------------------------------
  34. # 操作三:删除整列
  35. del(df['A'])
  36. print(df)
  37. '''
  38. calories duration
  39. day1 420 50
  40. day2 380 40
  41. day3 390 45
  42. '''

索引

基本介绍

  • 首先需要明确的是:Series和DataFrame中的索引都是Index对象

image.png
image.png

  • 索引对象不可变,保证了数据的安全
  • 常见的索引类型
    • Int64Index:整数索引
    • MultiIndex:层级索引
    • DatetimeIndex:时间戳索引

      Series的索引操作

      注意:loc是基于标签名的索引,iloc是基于索引编号的索引 ```python import pandas as pd

ser = pd.Series(range(5), index=[‘a’, ‘b’, ‘c’, ‘d’, ‘e’]) print(ser) ‘’’ a 0 b 1 c 2 d 3 e 4 dtype: int64

‘’’

方式一:行索引

print(ser[0]) # 0,可以使用ser.iloc[0]

print(ser[‘a’]) # 0,可以使用ser.loc[‘a’]

方式二:切片索引

print(ser[1:3]) # 可以使用ser.iloc[1:3] ‘’’ b 1 c 2 dtype: int64 ‘’’ print(ser[‘b’:’d’]) # 可以使用ser.loc[‘b’:’d’] ‘’’ b 1 c 2 d 3 dtype: int64

‘’’

方式三:不连续索引

print(ser[[0, 2, 4]]) # 可以使用ser.iloc[[0, 2, 4]] ‘’’ a 0 c 2 e 4 dtype: int64 ‘’’ print(ser[[‘a’, ‘e’]]) # 可以使用ser.loc[[‘a’, ‘e’]] ‘’’ a 0 e 4 dtype: int64

‘’’

方式四:布尔索引

print(ser > 2) ‘’’ a False b False c False d True e True dtype: bool ‘’’ print(ser[ser > 2]) ‘’’ d 3 e 4 dtype: int64 ‘’’

  1. <a name="qiPHd"></a>
  2. ### DataFrame的索引操作
  3. 注意:loc是基于标签名的索引,iloc是基于索引编号的索引
  4. ```python
  5. import pandas as pd
  6. import numpy as np
  7. df = pd.DataFrame(np.arange(12).reshape(3, 4), index=['a', 'b', 'c'], columns=['A', 'B', 'C', 'D'])
  8. print(df)
  9. '''
  10. A B C D
  11. a 0 1 2 3
  12. b 4 5 6 7
  13. c 8 9 10 11
  14. '''
  15. ---------------------------------------------------------
  16. # 方式一:列索引,没有行索引
  17. print(df['A']) # 不能使用df[0]
  18. '''
  19. a 0
  20. b 4
  21. c 8
  22. Name: A, dtype: int32
  23. '''
  24. print(type(df['A'])) # <class 'pandas.core.series.Series'>
  25. --------------------
  26. print(df[['A']]) # 不能使用df[[0]]
  27. '''
  28. A
  29. a 0
  30. b 4
  31. c 8
  32. '''
  33. print(type(df[['A']])) # <class 'pandas.core.frame.DataFrame'>
  34. ---------------------------------------------------------
  35. # 方式二:切片索引,只能用于行索引,不能用于列索引
  36. print(df['a':'a']) # # df['a':'a']等价于df[0:1]
  37. '''
  38. A B C D
  39. a 0 1 2 3
  40. '''
  41. --------------------
  42. print(df['a':'b']) # df['a':'b']等价于df[0:2]
  43. '''
  44. A B C D
  45. a 0 1 2 3
  46. b 4 5 6 7
  47. '''
  48. print(type(df['a':'b'])) # <class 'pandas.core.frame.DataFrame'>
  49. ---------------------------------------------------------
  50. # 方式三:不连续索引,只能用于列索引,不能用于行索引
  51. print(df[['A', 'C']]) # 不能使用df[[0, 2]]
  52. #
  53. '''
  54. A C
  55. a 0 2
  56. b 4 6
  57. c 8 10
  58. '''
  59. print(type(df[['A', 'C']])) # <class 'pandas.core.frame.DataFrame'>

loc和iloc的高级使用

对于DataFrame,loc和iloc是等价的,因此以iloc为例

  1. import pandas as pd
  2. import numpy as np
  3. df = pd.DataFrame(np.arange(12).reshape(3, 4), index=['a', 'b', 'c'], columns=['A', 'B', 'C', 'D'])
  4. print(df)
  5. '''
  6. A B C D
  7. a 0 1 2 3
  8. b 4 5 6 7
  9. c 8 9 10 11
  10. '''
  11. print(df.iloc[[0, 1], 0:3])
  12. '''
  13. A B C
  14. a 0 1 2
  15. b 4 5 6
  16. '''
  17. print(df.iloc[0:2, 0:3])
  18. '''
  19. A B C
  20. a 0 1 2
  21. b 4 5 6
  22. '''
  23. print(df.iloc[[0, 2]])
  24. '''
  25. A B C D
  26. a 0 1 2 3
  27. c 8 9 10 11
  28. '''
  29. print(df.iloc[:, 0:1])
  30. '''
  31. A
  32. a 0
  33. b 4
  34. c 8
  35. '''
  36. print(df.iloc[:, 0])
  37. '''
  38. a 0
  39. b 4
  40. c 8
  41. Name: A, dtype: int32
  42. '''
  43. print(df.iloc[0])
  44. '''
  45. A 0
  46. B 1
  47. C 2
  48. D 3
  49. Name: a, dtype: int32
  50. '''
  51. print(df.iloc[0, 0:2])
  52. '''
  53. A 0
  54. B 1
  55. Name: a, dtype: int32
  56. '''

对齐运算

Series的对齐运算

  1. import pandas as pd
  2. import numpy as np
  3. s1 = pd.Series(range(0, 3), index=range(3))
  4. s2 = pd.Series(range(10, 15), index=range(5))
  5. print(s1)
  6. '''
  7. 0 0
  8. 1 1
  9. 2 2
  10. dtype: int64
  11. '''
  12. print(s2)
  13. '''
  14. 0 10
  15. 1 11
  16. 2 12
  17. 3 13
  18. 4 14
  19. dtype: int64
  20. '''
  21. print(s1 + s2)
  22. '''
  23. 0 10.0
  24. 1 12.0
  25. 2 14.0
  26. 3 NaN
  27. 4 NaN
  28. dtype: float64
  29. '''
  30. print(s1.add(s2, fill_value=0))
  31. '''
  32. 0 10.0
  33. 1 12.0
  34. 2 14.0
  35. 3 13.0
  36. 4 14.0
  37. dtype: float64
  38. '''

DataFrame的对齐运算

  1. import pandas as pd
  2. import numpy as np
  3. df1 = pd.DataFrame(np.ones((2, 2)), columns=['a', 'b'])
  4. df2 = pd.DataFrame(np.ones((3, 3)), columns=['a', 'b', 'c'])
  5. print(df1)
  6. '''
  7. a b
  8. 0 1.0 1.0
  9. 1 1.0 1.0
  10. '''
  11. print(df2)
  12. '''
  13. a b c
  14. 0 1.0 1.0 1.0
  15. 1 1.0 1.0 1.0
  16. 2 1.0 1.0 1.0
  17. '''
  18. print(df1 + df2)
  19. '''
  20. a b c
  21. 0 2.0 2.0 NaN
  22. 1 2.0 2.0 NaN
  23. 2 NaN NaN NaN
  24. '''
  25. print(df1.add(df2, fill_value=0))
  26. '''
  27. a b c
  28. 0 2.0 2.0 1.0
  29. 1 2.0 2.0 1.0
  30. 2 1.0 1.0 1.0
  31. '''

使用函数

对于Series的操作和DataFrame基本类似,所以以DataFrame为例

可直接使用numpy的函数

  1. import pandas as pd
  2. import numpy as np
  3. df = pd.DataFrame(np.random.randn(2, 3) - 1)
  4. print(df)
  5. '''
  6. 0 1 2
  7. 0 -1.249877 1.732052 -2.438650
  8. 1 -1.240503 -0.739373 -1.734294
  9. '''
  10. print(np.abs(df))
  11. '''
  12. 0 1 2
  13. 0 1.249877 1.732052 2.438650
  14. 1 1.240503 0.739373 1.734294
  15. '''

通过apply将函数应用到行或列上

  1. import pandas as pd
  2. import numpy as np
  3. df = pd.DataFrame(np.random.randn(2, 3) - 1)
  4. print(df)
  5. '''
  6. 0 1 2
  7. 0 -0.961372 -1.083071 -0.950709
  8. 1 0.259989 1.168447 0.265873
  9. '''
  10. print(df.apply(lambda x: x.max())) # 默认是轴0,即自上而下
  11. '''
  12. 0 0.259989
  13. 1 1.168447
  14. 2 0.265873
  15. dtype: float64
  16. '''
  17. print(df.apply(lambda x: x.max(), axis=1)) # 指定为轴1,即自左而右
  18. '''
  19. 0 -0.950709
  20. 1 1.168447
  21. dtype: float64
  22. '''

通过applymap将函数应用到每个数据上

  1. import pandas as pd
  2. import numpy as np
  3. df = pd.DataFrame(np.random.randn(2, 3) - 1)
  4. print(df)
  5. '''
  6. 0 1 2
  7. 0 -0.171078 -0.951804 -2.561237
  8. 1 -0.944916 -2.440723 -1.218804
  9. '''
  10. print(df.applymap(lambda x: '%.2f' % x))
  11. '''
  12. 0 1 2
  13. 0 -0.17 -0.95 -2.56
  14. 1 -0.94 -2.44 -1.22
  15. '''
  16. print(df.applymap(lambda x: np.abs(x)))
  17. '''
  18. 0 1 2
  19. 0 0.171078 0.951804 2.561237
  20. 1 0.944916 2.440723 1.218804
  21. '''

排序操作

按索引进行排序

通过函数sort_index(),默认使用升序、按轴0进行排序,ascending=False为降序排序

  1. import pandas as pd
  2. import numpy as np
  3. df = pd.DataFrame(np.random.randn(3, 3),
  4. index=np.random.randint(3, size=3),
  5. columns=np.random.randint(3, size=3))
  6. print(df)
  7. '''
  8. 1 2 0
  9. 2 0.497309 -2.689734 -0.653441
  10. 0 1.245357 -0.563550 0.057072
  11. 2 -0.954434 -1.055197 -0.875219
  12. '''
  13. print(df.sort_index())
  14. '''
  15. 1 2 0
  16. 0 1.245357 -0.563550 0.057072
  17. 2 0.497309 -2.689734 -0.653441
  18. 2 -0.954434 -1.055197 -0.875219
  19. '''
  20. print(df.sort_index(axis=1, ascending=False))
  21. '''
  22. 2 1 0
  23. 2 -2.689734 0.497309 -0.653441
  24. 0 -0.563550 1.245357 0.057072
  25. 2 -1.055197 -0.954434 -0.875219
  26. '''

按值进行排序

通过函数sort_values(),需要通过by指定轴的名字;默认是按轴0进行排序,可以通过axis=1指定按轴1进行排序;默认是升序排序,可以通过ascending=False指定降序排序

  1. import pandas as pd
  2. import numpy as np
  3. df = pd.DataFrame(np.random.randn(3, 3), columns=['A', 'B', 'C'])
  4. print(df)
  5. '''
  6. A B C
  7. 0 -0.042903 -0.862099 1.253066
  8. 1 0.372508 0.492648 -0.416308
  9. 2 0.222194 -1.288317 -0.340111
  10. '''
  11. print(df.sort_values(by='A'))
  12. '''
  13. A B C
  14. 0 -0.042903 -0.862099 1.253066
  15. 2 0.222194 -1.288317 -0.340111
  16. 1 0.372508 0.492648 -0.416308
  17. '''
  18. print(df.sort_values(by=2, axis=1, ascending=False))
  19. '''
  20. A C B
  21. 0 -0.042903 1.253066 -0.862099
  22. 1 0.372508 -0.416308 0.492648
  23. 2 0.222194 -0.340111 -1.288317
  24. '''

处理缺失数据

  • is_null():判断是否为NaN
  • dropna(axis=0):丢弃包含NaN的行或列
  • fillna(num):用num替换其中的NaN ```python import pandas as pd import numpy as np

df = pd.DataFrame([np.random.randn(3), [1, 2, np.nan], [np.nan, 4, np.nan]])

print(df) ‘’’ 0 1 2 0 -1.628242 -0.226639 1.508853 1 1.000000 2.000000 NaN 2 NaN 4.000000 NaN ‘’’

print(df.isnull()) ‘’’ 0 1 2 0 False False False 1 False False True 2 True False True ‘’’

print(df.dropna()) ‘’’ 0 1 2 0 -1.628242 -0.226639 1.508853 ‘’’

print(df.dropna(axis=1)) ‘’’ 1 0 -0.226639 1 2.000000 2 4.000000 ‘’’

print(df.fillna(100)) ‘’’ 0 1 2 0 -1.628242 -0.226639 1.508853 1 1.000000 2.000000 100.000000 2 100.000000 4.000000 100.000000 ‘’’ ```