Pandas学习笔记(三)

Series对象(一)

目录

  • Series对象(一)
      • 导入本笔记需要用的包
      • 广播
      • 将Series传递给,Python任何内置函数,并产生一个可以预测的结果
      • 代码挑战
        • 解决方案:
  • Series方法
      • 排序
      • 用`value_counts`方法计算值的个数
      • 代码挑战
        • 解决方案

该文章内容为《Pandas数据分析实战》的学习笔记

导入本笔记需要用的包

import pandas as pd
import numpy as np

广播

s1 = pd.Series(
    data = [5, 10, 15],
    index = ['A', 'B', 'C']
)
s2 = pd.Series(
    data = [4, 8, 12, 14],
    index = ['B', 'C', 'D', 'E']
)
s1 + s2

会对相同索引值进行求和,如果一个索引在其中一个Series中存在,而在另外一个中不存在,则和为NaN

将Series传递给,Python任何内置函数,并产生一个可以预测的结果

cities = pd.Series(
    data = ["北京", "上海", "广州", "深圳"]
)
print(len(cities))
print(type(cities))
"上海" in cities

代码挑战

假设你有两个数据结构:

superheros = [
    "Batman",
    "Superman",
    "Spider-Man",
    "Iron Man",
    "Captain America",
    "Wonder Woman"
]
strength_levels = (100, 120, 90, 95, 110, 120)

要解决如下问题:

  1. 使用 superheroes 列表填充一个新的 Series 对象?
  2. 使用 strength_levels 元组填充一个新的 Series 对象?
  3. 创建一个 Series,将 superheroes 作为索引标签,strength_levels 作为值,并将 Series 赋值给 heroes 变量?
  4. 提取 heroes Series 的前两行?
  5. 提取 heroes Series 的后四行?
  6. 确定 heroes Series 中唯一值的数量?
  7. 计算 superheroes 的平均 strength
  8. 计算 superheroes 的最大和最小 strength
  9. 如何让每个 superheroesstrength 翻倍?
  10. 如何将 heroes Series 转换为 Python 字典?
解决方案:
# (1)
Index = pd.Series(data = superheros)
# (2)
Value= pd.Series(data = strength_levels)
# (3)
heros = pd.Series(data = strength_levels, index = superheros)
# (4)
heros.head(2)
# (5)
heros.tail(4)
# (6)
heros.nunique()
# (7)
heros.mean()
# (8)
heros.max()
heros.min()
# (9)
heros * 2
# (10)
dict(heros)

Series方法

使用read_csv函数导入数据集,read_csv函数的第一个参数filepath_or_buffer应该是一个最后带.csv后缀的文件或文件路径

无论数据集中有多少列,read_csv始终将数据导入为DataFrame

这里我们导入数据,并将其转成Series

pokemon = pd.read_csv("./pandas-in-action-master/chapter_03_series_methods/pokemon.csv", index_col = "Pokemon").squeeze()

同时我们还可以通过read_csv函数的parse_dates参数,接收一个字符串列表,表示列表中提到的列应该转换为日期时间类型

google = pd.read_csv("/Users/mima0000/Desktop/code/Python/Pandas/pandas-in-action-master/chapter_03_series_methods/google_stocks.csv",
                     parse_dates = ["Date"],
                     index_col = "Date").squeeze()

同时我们还可以通过usecols来选择导入的列

battles = pd.read_csv("/Users/mima0000/Desktop/code/Python/Pandas/pandas-in-action-master/chapter_03_series_methods/revolutionary_war.csv",
                      index_col = "Start Date",
                      parse_dates = ["Start Date"],
                      usecols = ["State", "Start Date"]).squeeze()

排序

google.sort_values().head()

可以通过ascending参数设置排序顺序,它的默认参数为True,为从小到大排序。若要从大到小排序,将参数设置为False

google.sort_values(ascending = False).head()

na_position参数用来设置遇到NaN值时,将记录放置在排序结果中的位置,该参数默认值为last,将排序结果放到末尾。若要首先显示缺失值,应将参数设置为first

battles.sort_values(na_position = "first")

删除NaN值,dropna()方法(仅针对Series值中的NaN,不针对索引)

battles.dropna().sort_values()

使用sort_index(),按索引排序

pokemon.sort_index().head()

使用nsmallestnlargest方法检索最小值和最大值

google.nsmallest(n = 6)
google.nlargest(n = 7)

其中n代表检索几个,默认为5

value_counts方法计算值的个数

pokemon.value_counts()

默认为降序进行排序,可以将ascending设置为True来升序排序

还可以让其返回占比,将normalize参数设置为True

pokemon.value_counts(normalize = True).head()

还可以通过数学运算和round方法来设置为一定精度的百分比

(pokemon.value_counts(normalize = True).head() * 100).round(2)

还可以通过设置bins来对区间进行统计

buckets = [0, 200, 400, 600, 800, 1000, 1200, 1400]
google.value_counts(bins = buckets)

注意这样返回的是根据统计值来排序的。我们可以根据索引排序来得到按间隔排序的结果

google.value_counts(bins = buckets).sort_index()

也可以

google.value_counts(bins = buckets, sort = False)

还可以给间隔数量让Pandas自己计算

google.value_counts(bins = 6).sort_index()

默认情况下value_counts会排出NaN值,可以像下面这样来对NaN也进行计数

battles.value_counts(dropna = False)

还可以通过index属性访问index对象

battles.index.value_counts()

代码挑战

假设一位历史学家需要确定美国独立战争期间星期几发生的战斗最多。最终的输出以星期几作为索引标签,并且以每天的战斗数作为值的Series。请使用revolutionary_war.csv数据集

可以使用下面的方法获得日期所在的星期几:

import datetime as dt
today = dt.datetime(2020, 12, 26)
today.strftime("%A")
解决方案
day_of_war = pd.read_csv("/Users/mima0000/Desktop/code/Python/Pandas/pandas-in-action-master/chapter_03_series_methods/revolutionary_war.csv",
                      parse_dates = ["Start Date"],
                      usecols = [ "Start Date"]).squeeze()
day_of_war

关注公众号小辛到处学,发送1,获取文中的数据资源

你可能感兴趣的:(Python,Pandas,pandas,笔记,python)