Pandas入门1(DataFrame+Series读写/Index+Select+Assign)

文章目录

    • 1. Creating, Reading and Writing
      • 1.1 DataFrame 数据框架
      • 1.2 Series 序列
      • 1.3 Reading 读取数据
    • 2. Indexing, Selecting, Assigning
      • 2.1 类python方式的访问
      • 2.2 Pandas特有的访问方式
        • 2.2.1 iloc 基于index访问
        • 2.2.2 loc 基于label标签访问
      • 2.3 set_index() 设置索引列
      • 2.4 Conditional selection 按条件选择
        • 2.4.1 布尔符号 `&,|,==`
        • 2.4.2 Pandas内置符号 `isin,isnull、notnull`
      • 2.5 Assigning data 赋值
        • 2.5.1 赋值常量
        • 2.5.2 赋值迭代的序列

learn from https://www.kaggle.com/learn/pandas

下一篇:Pandas入门2(DataFunctions+Maps+groupby+sort_values)

1. Creating, Reading and Writing

1.1 DataFrame 数据框架

  • 创建DataFrame,它是一张表,内部是字典,key :[value_1,...,value_n]
#%%
# -*- coding:utf-8 -*-
# @Python Version: 3.7
# @Time: 2020/5/16 21:10
# @Author: Michael Ming
# @Website: https://michael.blog.csdn.net/
# @File: pandasExercise.ipynb
# @Reference: https://www.kaggle.com/learn/pandas
import pandas as pd#%%
pd.DataFrame({'Yes':[50,22],"No":[131,2]})

在这里插入图片描述

fruits = pd.DataFrame([[30, 21],[40, 22]], columns=['Apples', 'Bananas'])

在这里插入图片描述

  • 字典内的value也可以是:字符串
pd.DataFrame({"Michael":['handsome','good'],"Ming":['love basketball','coding']})

在这里插入图片描述

  • 给数据加索引indexindex=['index1','index2',...]
pd.DataFrame({"Michael":['handsome','good'],"Ming":['love basketball','coding']},index=['people1 say','people2 say'])

在这里插入图片描述

1.2 Series 序列

  • Series 是一系列的数据,可以看成是 list
pd.Series([5,2,0,1,3,1,4])0    5
1    2
2    0
3    1
4    3
5    1
6    4
dtype: int64
  • 也可以把数据赋值给Series,只是Series没有列名称,只有总的名称
  • DataFrame本质上是多个Series在一起
pd.Series([30,40,50],index=['2018销量','2019销量','2020销量'],name='博客访问量')2018销量    30
2019销量    40
2020销量    50
Name: 博客访问量, dtype: int64

1.3 Reading 读取数据

  • 读取csv("Comma-Separated Values")文件,pd.read_csv('file'),存入一个DataFrame
wine_rev = pd.read_csv("winemag-data-130k-v2.csv")
wine_rev.shape # 大小
(129971, 14)
wine_rev.head() # 查看头部5行

在这里插入图片描述

  • 可以自定义索引列,index_col=, 可以是列的序号,或者是列的 name
wine_rev = pd.read_csv("winemag-data-130k-v2.csv", index_col=0)
wine_rev.head()

(下图比上面少了一列,因为定义了index列为0列)
在这里插入图片描述

  • 保存,to_csv('xxx.csv')
wine_rev.to_csv('XXX.csv')

2. Indexing, Selecting, Assigning

2.1 类python方式的访问

item.col_name # 缺点,不能访问带有空格的名称的列,[]操作可以
item['col_name']
wine_rev.country
wine_rev['country']0            Italy
1         Portugal
2               US
3               US
4               US...   
129966     Germany
129967          US
129968      France
129969      France
129970      France
Name: country, Length: 129971, dtype: object
wine_rev['country'][0]   # 'Italy',先取列,再取行
wine_rev.country[1]  # 'Portugal'

2.2 Pandas特有的访问方式

2.2.1 iloc 基于index访问

  • 要选择DataFrame中的第一数据,我们可以使用以下代码:

  • wine_rev.iloc[0]

country                                                              Italy
description              Aromas include tropical fruit, broom, brimston...
designation                                                   Vulkà Bianco
points                                                                  87
price                                                                  NaN
province                                                 Sicily & Sardinia
region_1                                                              Etna
region_2                                                               NaN
taster_name                                                  Kerin O’Keefe
taster_twitter_handle                                         @kerinokeefe
title                                    Nicosia 2013 Vulkà Bianco  (Etna)
variety                                                        White Blend
winery                                                             Nicosia
Name: 0, dtype: object

lociloc都是行第一,列第二,跟上面python操作是相反的

  • wine_rev.iloc[:,0],获取第一: 表示所有的
0            Italy
1         Portugal
2               US
3               US
4               US...   
129966     Germany
129967          US
129968      France
129969      France
129970      France
Name: country, Length: 129971, dtype: object
  • wine_rev.iloc[:3,0]:3 表示 [0:3)行 0,1,2
0       Italy
1    Portugal
2          US
Name: country, dtype: object
  • 也可以用离散的list,来取行,wine_rev.iloc[[1,2],0]
1    Portugal
2          US
Name: country, dtype: object
  • 取最后几行,wine_rev.iloc[-5:],倒数第5行到结束

在这里插入图片描述

2.2.2 loc 基于label标签访问

  • wine_rev.loc[0, 'country'],行也可以使用 [0,1]表示离散行,列不能使用index
'Italy'
  • wine_rev.loc[ : 3, 'country'],跟iloc不一样,这里包含了3号行loc包含末尾的
0       Italy
1    Portugal
2          US
3          US
Name: country, dtype: object
  • wine_rev.loc[ 1 : 3, ['country','points']],多列用 list 括起来

在这里插入图片描述

  • loc优势,例如有用字符串 index 的行,df.loc['Apples':'Potatoes']可以选取

2.3 set_index() 设置索引列

  • set_index() 可以重新设置索引,wine_rev.set_index("title")

在这里插入图片描述

2.4 Conditional selection 按条件选择

2.4.1 布尔符号 &,|,==

  • wine_rev.country == 'US',按国家查找, 生成了Series of True/False,可用于 loc
0         False
1         False
2          True
3          True
4          True...  
129966    False
129967     True
129968    False
129969    False
129970    False
Name: country, Length: 129971, dtype: bool
  • wine_rev.loc[wine_rev.country == 'US'],把 US 的行全部选出来

在这里插入图片描述

  • wine_rev.loc[(wine_rev.country == 'US') & (wine_rev.points >= 90)],US的&且得分90以上的
  • 还可以用 | 表示(像C++的位运算符号)

在这里插入图片描述

2.4.2 Pandas内置符号 isin,isnull、notnull

  • wine_rev.loc[wine_rev.country.isin(['US','Italy'])],只选 US 和 Italy 的行

在这里插入图片描述

  • wine_rev.loc[wine_rev.price.notnull()],价格不为空的
  • wine_rev.loc[wine_rev.price.isnull()],价格为NaN的

2.5 Assigning data 赋值

2.5.1 赋值常量

  • wine_rev['critic'] = 'Michael',新加了一列
  • wine_rev.country = 'Ming',已有的列的value会直接被覆盖

在这里插入图片描述

2.5.2 赋值迭代的序列

  • wine_rev['test_id'] = range(len(wine_rev),0,-1)

在这里插入图片描述


下一篇:Pandas入门2(DataFunctions+Maps+groupby+sort_values)

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/475813.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

关于Visual C#.NET数据库开发经典案例解析(附光盘两张)(珍藏版)—的读后感...

关于Visual C#.NET数据库开发经典案例解析(附光盘两张)(珍藏版)— 评论读后感:里面的内容很经典,很实用读后感:给初学者是好,但是是比较旧的了!VS2003 C/S的读后感&#…

linux git还原文件,Gitlab备份到windows、在Linux恢复

一 备份gitlab为完整压缩包# 在目录/var/opt/gitlab/backups/ 创建备份文件gitlab-rake gitlab:backup:create/var/opt/gitlab/backups/1559614181_2019_06_04_10.7.7_gitlab_backup.tar查看备份文件夹容量df -h /var/opt/gitlab/backups二 恢复gitlab复制gitlab_backup.tar到对…

LeetCode 372. 超级次方(快速幂)

1. 题目 你的任务是计算 ab 对 1337 取模,a 是一个正整数,b 是一个非常大的正整数且会以数组形式给出。 示例 1: 输入: a 2, b [3] 输出: 8示例 2: 输入: a 2, b [1,0] 输出: 1024来源:力扣(LeetCode) 链接&…

c#让电脑锁定、注销、关机

代码 usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel;usingSystem.Data;usingSystem.Drawing;usingSystem.Linq;usingSystem.Text;usingSystem.Windows.Forms;usingMicrosoft.Win32;usingSystem.Runtime.InteropServices;usingSystem.IO;usingSystem…

linux错误自动报告工具,linux – 关闭abrt的电子邮件通知(自动错误报告工具)

我正在配置CentOS 6.2并且已经看到了一些“[abrt]完整崩溃报告”电子邮件.我知道abrt对于创建崩溃转储非常有用,所以我不想禁用该服务,我只是想停止获取崩溃报告电子邮件.我可能不得不在/etc/abrt/abrt.conf中添加一些配置文件.我似乎无法在搜索中找到任何内容.任何的想法&…

Pandas入门2(DataFunctions+Maps+groupby+sort_values)

文章目录3. Summary Functions and Maps3.1 Summary Functions 数据总结函数3.1.1 describe()3.1.2 mean(),median(),idxmax(),unique(),value_counts()3.2 Maps 映射3.2.1 map()3.2.2 apply()3.2.3 内置转换方法4. Grouping and …

Adobe和苹果相互推诿 不支持Flash谁之过?

针对苹果CEO史蒂夫乔布斯 (Steve Jobs)的指责,Adobe CTO凯文林奇(Kevin Lynch)日前给予回应,称苹果iPad不支持Flash完全是苹果的错。上周三,苹果发布了业内期待已久的平板电脑iPad,但由于不支持 Flash而遭到了用户抱怨。对此&…

linux视频在windows播放器,适用于Windows和Linux的免费多媒体播放器SMPlayer 18.6.0发布 - 爱绿豆...

SMPlayer是一个很好的 MPlayer 电影播放程序前端,可以支持大部分的视频和音频文件。它支持音频轨道切换,允许调节亮度、对比度、色调、饱和度、伽玛值,按照倍速、4倍速等多种速度回放,还可以进行音频和字幕延迟调整以同步音频和字…

LeetCode 393. UTF-8 编码验证(位运算)

1. 题目 UTF-8 中的一个字符可能的长度为 1 到 4 字节,遵循以下的规则: 对于 1 字节的字符,字节的第一位设为0,后面7位为这个符号的unicode码。对于 n 字节的字符 (n > 1),第一个字节的前 n 位都设为1&#xff0c…

OA 办公系统 模块设计

--连接主数据库 use Master go --如果数据库simpleoa 存在,则先删除simpleoa。 if exists (select * from sysdatabases where namesimpleoa) drop database simpleoa go--创建simpleoa数据库 create database simpleoa go-- use simpleoa go--创建用户表 create…

通过java理解linux,Java继承的理解

继承:1)概念把多个类中相同的成员给提取出来定义到一个独立的类中。然后让这多个类和该独立的类产生一个关系,这多个类就具备了这些内容。这个关系叫继承。1.1)定义类时,通过“继承”一个现有的类,子类可以具有父类中的所有属性和…

LeetCode 373. 查找和最小的K对数字(自定义优先队列BFS)

1. 题目 给定两个以升序排列的整形数组 nums1 和 nums2, 以及一个整数 k。 定义一对值 (u,v),其中第一个元素来自 nums1,第二个元素来自 nums2。 找到和最小的 k 对数字 (u1,v1), (u2,v2) … (uk,vk)。 示例 1: 输入: nums1 [1,7,11], nums2 [2,4,…

Android中使用Thread线程出现的问题

很多初入Android或Java开发的新手对Thread、Looper、Handler和Message仍然比较迷惑,衍生的有HandlerThread、java.util.concurrent、Task、AsyncTask由于目前市面上的书籍等资料都没有谈到这些问题,今天Android123就这一问题做更系统性的总结.  Androi…

linux防火墙的复规则,Centos下iptables防火墙规则编辑方法 - YangJunwei

今天整理一下Centos下iptables防火墙规则的保存、清除等编辑方法。如已经安装,请跳过。$ yum install iptables二、查看 iptables 防火墙已有规则以下四种方法任选其一即可。$ service iptables status$ /etc/init.d/iptables status (此方法为上一方法的路径执行版…

Blend设计VSM

Silverlight中的ControlTemplate(1)-概念 Silverlight中的ControlTemplate(2)-概念 Silverlight中的ControlTemplate(3)-Blend设计ControlTemplate 上一篇我是通过Blend简单的演示如何修改ControlTemplate,这一篇关注VSM这个部分。 概念的东…

Pandas入门3(dtype+fillna+replace+rename+concat+join)

文章目录5. dtype 数据类型6. Missing data 缺失值6.1 查找缺失值 pd.isnull(),pd.notnull()6.2 填补缺失值 fillna(),replace()7. Renaming and Combining 重命名、合并7.1 Renaming 重命名7.2 Combining 合并数据learn from https://www.kaggle.com/l…

Linux连接状态为syn_recv,linux 服务器 syn*** 大量SYN_RECV状态处理

1、查看连接状态netstat -nat | awk /^tcp/{S[$NF]}END{for (a in S) print a,S[a]}SYN_RECV表示正在等待处理的请求数;ESTABLISHED表示正常数据传输状态;TIME_WAIT表示处理完毕,等待超时结束的请求数。状态:描述CLOSED&#xff1…

LeetCode 388. 文件的最长绝对路径(不用栈,前缀和)

1. 题目 假设我们以下述方式将我们的文件系统抽象成一个字符串: 字符串 "dir\n\tsubdir1\n\tsubdir2\n\t\tfile.ext" 表示: dirsubdir1subdir2file.ext目录 dir 包含一个空的子目录 subdir1 和一个包含一个文件 file.ext 的子目录 subdir2 。 字符串 "dir\n…

使用Delphi自带的TDockTabSet组件实现停靠功能(Jeremy North)

源地址:http://edn.embarcadero.com/article/33446 摘要: Instructions on how to use the TDockTabSet component to make advanced docking user interfaces. Introduction This article discusses the use of the TDockTabSet component that was originally int…

linux下面 r和 n的区别,【冷知识】关于/r与/n以及 /r/n 的区别总结

首先:\r就是"回到行首",\n就是"到下一行"即:\r是回车,\n是换行,前者使光标到行首,后者使光标下移一格。通常用的Enter是两个加起来的,即\r\n直接这么说你可能没啥感觉,但是真正到了编码…