数据分析(六)之pandas学习【Series创建、切片、索引和读取外部数据】

数据分析学习线路图

在这里插入图片描述

为什么要学习pandas?

那么问题来了:numpy已经能够帮助我们处理数据,能够结合matplotlib解决我们数据分析的问题,那么pandas学习的目的在什么地方呢?

  1. numpy能够帮我们处理处理数值型数据,但是这还不够
  2. 很多时候,我们的数据除了数值之外,还有字符串,还有时间序列等
  3. 比如:我们通过爬虫获取到了存储在数据库中的数据
  4. 比如:之前youtube的例子中除了数值之外还有国家的信息,视频的分类(tag)信息,标题信息等

所以, numpy能够帮助我们处理数值,但是pandas除了处理数值之外(基于numpy),还能够帮助我们处理其他类型的数据

1、pandas常用数据类型

  1. Series 一维,带标签数组
  2. DataFrame 二维,Series容器

1.1 pandas之Series创建

在这里插入图片描述

# coding=utf-8
import pandas as pd
import string

# a = pd.Series([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], index=['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'])

a = {string.ascii_uppercase[i]: i for i in range(10)}

print(pd.Series(a))

# 如果是字典类型呢?
temp_dict = dict(name="xiaoping", age=20, tel=100086)

b = pd.Series(temp_dict)

print(b)

c = pd.Series([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
print(c)

输出结果:
A    0
B    1
C    2
D    3
E    4
G    6
H    7
I    8
J    9
dtype: int64

name    xiaoping
age           20
tel       100086
dtype: object

0    0
1    1
2    2
3    3
4    4
5    5
6    6
7    7
8    8
9    9
dtype: int64

1.2 pandas之Series切片和索引

在这里插入图片描述
对于一个陌生的series类型,我们如何知道他的索引和具体的值呢?

在这里插入图片描述
点击百度搜索:
在这里插入图片描述
Series.where(cond, other=nan, inplace=False, axis=None, level=None, errors=‘raise’, try_cast=False)

  • 参数
    • cond:bool 系列/数据帧、阵列式或可调用式

      • 如果cond为 True,请保留原始值。如果为 False,则替换为来自其他 的相应值。如果cond是可调用的,则在系列/数据帧上计算,并且应返回布尔系列/数据帧或阵列。可调用的不得更改输入系列/数据帧(尽管熊猫不检查它)。
    • other:标量、系列/数据帧或可调用

      • cond为 false的条目将替换为来自其他 的相应值。如果其他是可调用的,则在系列/数据帧上计算,并返回标量或系列/数据帧。可调用的不得更改输入系列/数据帧(尽管熊猫不检查它)。
    • inplace:布尔, 默认错误

      • 是否对数据执行就地执行的操作。
    • axis:int,默认为"无"

      • 如果需要,对齐轴。
    • level:int,默认为无

      • 如果需要,对齐级别。
    • errors:str, [“引发”, “忽略”}, 默认 “引发”

      • 请注意,当前此参数不会影响结果,并且始终强制使用合适的 dtype。
      • “引发”:允许引发异常。
      • “忽略”:禁止显示异常。错误时返回原始对象。
    • try_cast:布尔, 默认错误

      • 尝试将结果转换回输入类型(如果可能)。
import numpy as np
import pandas as pd
import string

s = pd.Series(range(5))

print(s.where(s > 0))
print(s.mask(s > 0))
print(s.where(s > 1, 10))  # 小于1的替换为10
输出结果:
0    NaN
1    1.0
2    2.0
3    3.0
4    4.0
dtype: float64

0    0.0
1    NaN
2    NaN
3    NaN
4    NaN
dtype: float64

0    10
1    10
2     2
3     3
4     4
dtype: int64

1.3 pandas之读取外部数据

在这里插入图片描述在这里插入图片描述

import pandas as pd

# pandas读取csv中的文件
df = pd.read_csv("./dogNames2.csv")

print(df[(800 < df["Count_AnimalName"]) | (df["Count_AnimalName"] < 1000)])
输出结果
      Row_Labels  Count_AnimalName
0              1                 1
1              2                 2
2          40804                 1
3          90201                 1
4          90203                 1
...          ...               ...
16215      37916                 1
16216      38282                 1
16217      38583                 1
16218      38948                 1
16219      39743                 1

[16220 rows x 2 columns]

读取mongodb中的数据
改进与进阶练习请看下章dataframe的学习

from pymongo import MongoClient
import pandas as pd

client = MongoClient()
collection = client["douban"]["tv1"]

data = list(collection.find())

t1 = data[0]
t1 = pd.Series(t1)

print(t1)
输出显示:
E:\PycharmProjects\untitled\venv\Scripts\python.exe E:/PycharmProjects/untitled/数据分析/day03_pandas/page108.py
_id                                          59ba7f9b421aa91b08a43faa
info                          王伟/潘粤明/王泷正/梁缘/剧情/犯罪/悬疑/2017-08-30(中国大陆)
original_price                                                   None
release_date                                                    08.30
rating                        {'count': 23043, 'max': 10, 'value': 9}
description                                                          
title                                                            白夜追凶
url                      https://m.douban.com/movie/subject/26883064/
price                                                            None
cover               {'url': 'https://qnmob2.doubanio.com/view/movi...
uri                                   douban://douban.com/tv/26883064
actions                                                         [可播放]
label                                                            None
subtype                                                              
directors                                                        [王伟]
actors                                                 [潘粤明, 王泷正, 梁缘]
date                                                             None
reviewer_name                                                        
forum_info          {'id': 'tv/26883064', 'participant_count': 453...
type                                                               tv
id                                                           26883064
tv_category                                                   chinese
tv_url_parameter                               filter_tv_domestic_hot
total_num                                                        None
parse_url           https://m.douban.com/rexxar/api/v2/subject_col...
total                                                            2123
dtype: object

Process finished with exit code 0

本小结注意事项

在运行读取mongodb中的数据 的代码的时候,下载mongoDB出现的问题:



  1. 安装mongoDB一直处于安装状态,安装不成功!
    解决办法:选择自定义安装(Coustom)
    紧接着把下面图片中的复选框 勾掉,不选 这是mongoDB的图形用户界面,可以不选,如果想要安装可以等mongoDB安装完成后,独立安装。

在这里插入图片描述




2.刚刚安装的 mongodb数据库文件缺失很多工具,需要单独下载
下载工具集
将下载的工具集文件bin里的工具都复制到原先下载的mongodb的bin目录下即可




3. 在使用mongoresotore命令导入(douban)数据库时,一直错误
原因是该命令是在进入cmd命令是运行的,而不是运行后mongo再运行的
图1是正确的
在这里插入图片描述在这里插入图片描述

最后附上mongoDB中运行的豆瓣数据集,下载后,使用mongoresotore命令恢复数据库即可。详细教程参考: 19 MongoDB数据库(还未写博客内容)豆瓣数据集如下:

豆瓣数据集

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值