当前位置:   article > 正文

pandas 基础API_pandas api

pandas api
  1. import pandas as pd
  2. import numpy as np
  3. import matplotlib.pyplot as plt
  4. '''
  5. Series
  6. 创建pd.Series(data=None, index=None, dtype=None)
  7. '''
  8. # s1 = pd.Series(np.arange(1, 10, 1))
  9. # print(s1.values) # 数据
  10. # print(s1.index) # 索引
  11. # print(s1.index.values) # 索引数据
  12. # color_count = pd.Series({'red': 100, 'blue': 200, 'green': 500, 'yellow': 1000})
  13. # print(color_count['red']) # 使用索引来获取数据
  14. '''
  15. DataFrame
  16. 创建pd.DataFrame(data=None, index=None, columns=None)
  17. index:行标签 axis=0
  18. columns:列标签 axis=1
  19. '''
  20. score = np.random.randint(50, 100, (10, 5))
  21. score_df = pd.DataFrame(score)
  22. # print(score_df)
  23. # print(score_df.shape) # (10,5) m行 n列
  24. # stu = ['同学' + str(i) for i in range(score_df.shape[0])]
  25. # score_df.index = stu # 设置行索引
  26. # score_df.columns = ["语文", "数学", "英语", "政治", "体育"]
  27. # print(score_df)
  28. # print(score_df)
  29. subjects = ["语文", "数学", "英语", "政治", "体育"]
  30. stu = ['stu' + str(i) for i in range(score_df.shape[0])]
  31. data = pd.DataFrame(score, columns=subjects, index=stu)
  32. # print(data)
  33. # print(data.columns.get_indexer(["体育", "政治"]))
  34. # print(data['语文'])
  35. # print(data['语文']['同学0'])
  36. # print(data.columns)
  37. # print(data.index)
  38. # print(data.values)
  39. # print(data.T) # 转置
  40. # data.head(5) # 显示前5行内容
  41. # data.tail(5) # 显示后5行内容
  42. # print(data.sort_values(by="数学", ascending=False))
  43. # print(data.sort_values(by=["数学", "语文"], ascending=False))
  44. # print(data['数学'] > 80)
  45. # print(data[data['数学'] > 80]) # 得到数学大于80
  46. # print(data[(data['数学'] > 65) & (data['语文'] < 85)])
  47. # print(data.query('数学>65 & 语文<85'))
  48. # print(data['数学'].isin([60, 70, 80]))
  49. # print(data[data['数学'].isin([60, 70, 80])])
  50. '''
  51. 用统计函数:0 代表列求结果, 1 代表行求统计结果
  52. max()、min()
  53. std():标准差
  54. var():方差
  55. median():中位数
  56. idxmax():求出最大值的位置
  57. idxmin():求出最小值的位置
  58. cumsum(): 累计和
  59. cummax(): 当前最大值
  60. cummin(): 当前最小值
  61. cumprod(): 累积
  62. apply() : 自定义函数
  63. '''
  64. # print(data.describe())
  65. # print(data.max(axis=0)) # axis=0 列 即每个学科最高分
  66. # print(data.max(axis=1)) # axis=1 行 即每个同学最高分
  67. # print(data[['数学', '英语']].apply(lambda x: x.max() - x.min(), axis=0)) # 分别得到数学和英语最大值最小值的分差
  68. # math = data['数学']
  69. # print(math.cummax())
  70. '''
  71. Pandas画图
  72. pd.DataFrame.plot(kind='line')
  73. line : 折线图
  74. bar : 条形图
  75. barh : 横放的条形图
  76. hist : 直方图
  77. pie : 饼图
  78. scatter: 散点图
  79. kind : str,需要绘制图形的种类
  80. '''
  81. # math.plot()
  82. # plt.show()
  83. '''
  84. 文件读取与存储
  85. pd.read_csv(filepath_or_buffer, sep =',', usecols)
  86. filepath_or_buffer:文件路径
  87. sep :分隔符,默认用","隔开
  88. usecols:指定读取的列名,列表形式
  89. DataFrame.to_csv(path_or_buf=None, sep=', ’, columns=None, header=True, index=True, mode='w', encoding=None)
  90. path_or_buf :文件路径
  91. sep :分隔符,默认用","隔开
  92. columns :选择需要的列索引
  93. header :boolean or list of string, default True,是否写进列索引值
  94. index:是否写进行索引
  95. mode:‘w’:重写, ‘a’ 追加
  96. pd.read_json(path_or_buf=None, orient=None, typ='frame', lines=False)
  97. path_or_buf : 路径
  98. orient : string,以什么样的格式显示.下面是5种格式:
  99. 1.split 将索引总结到索引,列名到列名,数据到数据。将三部分都分开了
  100. 2.recordscolumnsvalues的形式输出
  101. 3.indexindex:{columnsvalues}…的形式输出
  102. 4.columnscolumns:{index:values}的形式输出
  103. 5.values 直接输出值
  104. lines : boolean, default False
  105. typ : default ‘frame’, 指定转换成的对象类型series或者dataframe
  106. DataFrame.to_json(path_or_buf=None, orient=None, lines=False) 将Pandas 对象存储为json格式
  107. path_or_buf=None:文件地址
  108. orient:存储的json形式,{‘split’,’records’,’index’,’columns’,’values’}
  109. lines:一个对象存储为一行
  110. '''
  111. # data.to_csv("data_v1.csv", header=True, index=True)
  112. # print(pd.read_csv("data_v1.csv"))
  113. # json_df = pd.read_json("1.json", orient="records", lines=True)
  114. # print(json_df)
  115. # print(pd.isnull(data)) # 判断是否是缺失值,是则返回False
  116. # print(np.all(pd.isnull(data))) # np.all()只要有一个就返回False
  117. #
  118. # print(pd.notnull(data)) # 判断是否是缺失值,是则返回True
  119. # print(np.all(pd.notnull(data))) # np.all()只要有一个就返回Ture
  120. '''
  121. 数据离散化
  122. '''
  123. # 自行分组
  124. # qcut = pd.qcut(data['数学'], 10)
  125. # 计算分到每个组数据个数
  126. # print(qcut)
  127. # print(qcut['stu0']) # 学生1在哪个区间
  128. # print(qcut.value_counts()) # 统计每个分组中有多少数据
  129. # 自定义区间分组
  130. # bins = [50, 60, 70, 80, 90, 100]
  131. # p_counts = pd.cut(data['数学'], bins)
  132. # print(p_counts.value_counts())
  133. # 分组与聚合
  134. col = pd.DataFrame({'color': ['white', 'red', 'green', 'red', 'green'],
  135. 'object': ['pen', 'pencil', 'pencil', 'ashtray', 'pen'],
  136. 'price1': [5.56, 4.20, 1.30, 0.56, 2.75],
  137. 'price2': [4.75, 4.12, 1.60, 0.75, 3.15]})
  138. print(col)
  139. print(col.groupby(['color'])['price1'].mean()) # 按color分组,再取出price1列求平均值
  140. print(col['price1'].groupby(col['color']).mean()) # 按color分组,再取出price1列求平均值
  141. print(col.groupby(['color'], as_index=False)['price1'].mean()) # 分组,数据的结构不变
  142. col.groupby(['color'])['object'].count().plot(kind='bar')
  143. plt.show()
  144. df = pd.DataFrame({'month': [1, 4, 7, 10],
  145. 'year': [2012, 2014, 2013, 2014],
  146. 'sale': [55, 40, 84, 31]})
  147. # print(df)
  148. # df = df.set_index('month')
  149. # df = df.set_index(['month', 'year'])
  150. # print(df)
  151. # print(df.index)
  152. # print(df.index.names)
  153. # print(df.index.levels)
  154. # csv_df = pd.read_csv("data.csv")
  155. # print(csv_df)
  156. # print(csv_df.loc[1:2, 'score'])

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/盐析白兔/article/detail/792023
推荐阅读
  

闽ICP备14008679号