Pandas基本数据对象及操作

2023-11-18

1、Series

创建Series
import pandas as pd
countries = ['中国', '美国', '澳大利亚']
countries_s = pd.Series(countries)
print(type(countries_s))
print(countries_s)

numbers = [4, 5, 6]
print(pd.Series(numbers))

country_dicts = {'CH': '中国',
                'US': '美国',
                'AU': '澳大利亚'}
country_dict_s = pd.Series(country_dicts)
# 给索引命名
country_dict_s.index.name = 'Code'
# 给数据命名
country_dict_s.name = 'Country'
print(country_dict_s)
print(country_dict_s.values)
print(country_dict_s.index)

处理缺失数据
countries = ['中国', '美国', '澳大利亚', None]
print(pd.Series(countries))
numbers = [4, 5, 6, None]
print(pd.Series(numbers))
country_dicts = {'CH': '中国',
                'US': '美国',
                'AU': '澳大利亚'}
country_dict_s = pd.Series(country_dicts)
print(country_dict_s)

# 通过索引判断数据是存在
# Series也可看作定长、有序的字典
print('CH' in country_dict_s)
print('NZ' in country_dict_s)
print('iloc:', country_dict_s.iloc[1])
print('loc:', country_dict_s.loc['US'])
print('[]:', country_dict_s['US'])
print('iloc:\n', country_dict_s.iloc[ [0, 2] ])
print()
print('loc:\n', country_dict_s.loc[['US', 'AU']])

向量化操作
import numpy as np
s = pd.Series(np.random.randint(0, 1000, 10000))
print(s.head())
print(len(s))

2、DataFrame

创建Dataframe
import pandas as pd
country1 = pd.Series({'Name': '中国',
                    'Language': 'Chinese',
                    'Area': '9.597M km2',
                     'Happiness Rank': 79})
country2 = pd.Series({'Name': '美国',
                    'Language': 'English (US)',
                    'Area': '9.834M km2',
                     'Happiness Rank': 14})
country3 = pd.Series({'Name': '澳大利亚',
                    'Language': 'English (AU)',
                    'Area': '7.692M km2',
                     'Happiness Rank': 9})
df = pd.DataFrame([country1, country2, country3], index=['CH', 'US', 'AU'])
# 注意在jupyter中使用print和不使用print的区别
print(df)
# 添加数据
# 如果个数小于要求的个数,会自动进行“广播”操作
# 如果大于要求的个数,会报错
df['Location'] = '地球'
print(df)
df['Region'] = ['亚洲', '北美洲', '大洋洲']
print(df)
Dataframe索引
# 行索引
print('loc:')
print(df.loc['CH'])
print(type(df.loc['CH']))
print('iloc:')
print(df.iloc[1])
print(df['Area'])
# 列索引
print(df['Area'])
print(type(df['Area']))
# 获取不连续的列数据
print(df[['Name', 'Area']])
# 混合索引
# 注意写法上的区别
print('先取出列,再取行:')
print(df['Area']['CH'])
print(df['Area'].loc['CH'])
print(df['Area'].iloc[0])
print('先取出行,再取列:')
print(df.loc['CH']['Area'])
print(df.iloc[0]['Area'])
# 转换行和列
print(df.T)
删除数据
print(df.drop(['CH']))
# 注意drop操作只是将修改后的数据copy一份,而不会对原始数据进行修改
print(df)
print(df.drop(['CH'], inplace=True))
# 如果使用了inplace=True,会在原始数据上进行修改,同时不会返回一个copy
print(df)
#  如果需要删除列,需要指定axis=1
print(df.drop(['Area'], axis=1))
print(df)
# 也可直接使用del关键字
del df['Name']
print(df)
DataFrame的操作与加载
print(df['Happiness Rank'])
# 注意从DataFrame中取出的数据进行操作后,会对原始数据产生影响
ranks = df['Happiness Rank']
ranks += 2
print(ranks)
print(df)
# 注意从DataFrame中取出的数据进行操作后,会对原始数据产生影响
# 安全的操作是使用copy()
ranks = df['Happiness Rank'].copy()
ranks += 2
print(ranks)
print(df)
# 加载csv文件数据
reprot_2015_df = pd.read_csv('./2015.csv')
print('2015年数据预览:')
#print(reprot_2015_df.head())
reprot_2015_df.head()
print(reprot_2015_df.info())

3、索引

[数据集2016.csv下载地址]
https://pan.baidu.com/s/1_D8rTk1Kl5io1qnBXMXhcA
密码:u2vt
# 使用index_col指定索引列
# 使用usecols指定需要读取的列
reprot_2016_df = pd.read_csv('./2016.csv', 
                             index_col='Country',
                             usecols=['Country', 'Happiness Rank', 'Happiness Score', 'Region'])
# 数据预览
reprot_2016_df.head()
print('列名(column):', reprot_2016_df.columns)
print('行名(index):', reprot_2016_df.index)
# 注意index是不可变的
reprot_2016_df.index[0] = '丹麦'
# 重置index
# 注意inplace加与不加的区别
reprot_2016_df.reset_index(inplace=True)
print(reprot_2016_df.head())
# 重命名列名
reprot_2016_df = reprot_2016_df.rename(columns={'Region': '地区', 'Hapiness Rank': '排名', 'Hapiness Score': '幸福指数'})
reprot_2016_df.head()
# 重命名列名,注意inplace的使用
reprot_2016_df.rename(columns={'Region': '地区', 'Happiness Rank': '排名', 'Happiness Score': '幸福指数'},
                     inplace=True)
reprot_2016_df.head()

4、Boolean Mask

print(reprot_2016_df.head())
# 过滤 Western Europe 地区的国家
# only_western_europe = reprot_2016_df['地区'] == 'Western Europe'
reprot_2016_df[reprot_2016_df['地区'] == 'Western Europe']
# 过滤 Western Europe 地区的国家
# 并且排名在10之外
only_western_europe_10 = (reprot_2016_df['地区'] == 'Western Europe') & (reprot_2016_df['排名'] > 10)
only_western_europe_10
# 叠加 boolean mask 得到最终结果
reprot_2016_df[only_western_europe_10]
# 熟练以后可以写在一行中
reprot_2016_df[(reprot_2016_df['地区'] == 'Western Europe') & (reprot_2016_df['排名'] > 10)]

5、层级索引

[数据集2015.csv下载地址]
https://pan.baidu.com/s/1-tBedyPvbuKQFJP5BdR1yA
密码:j22j
print(reprot_2015_df.head())
# 设置层级索引
report_2015_df2 = reprot_2015_df.set_index(['Region', 'Country'])
report_2015_df2.head(20)
# level0 索引
report_2015_df2.loc['Western Europe']
# 两层索引
report_2015_df2.loc['Western Europe', 'Switzerland']
# 交换分层顺序
report_2015_df2.swaplevel()
# 排序分层
report_2015_df2.sort_index(level=0)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Pandas基本数据对象及操作 的相关文章

随机推荐

  • Linux中Ubuntu卡顿问题解决

    解决vmware虚拟机速度慢的3种方法 使用vmware虚拟操作系统的好处不用多说 但如果虚拟机运行速度十分缓慢 正常使用很卡的话是很痛苦的 本文介绍了3种提高虚拟机运行速度的方法 都是古意人实际操作过的方法 效果显著 推荐大家一试 1 给
  • 【复习】软考中级_软件设计师(2021)__上午

    前言 1 总想瞎bb点什么内容 2 自己复习的笔记 分享大家一起使用 3 可能有错误请指教 4 对于有些基础内容进行省略 5 适合等公交 摸鱼 无聊的时候观看 6 技术有限 哪里出错误了请指教 十分感谢 一 计算机组成与结构 数据的转换 1
  • 【C++ Primer 第五版】 目录-第Ⅰ部分

    序言和前言 第一章 开始 1 1 编解一个简单的C 程序 1 1 1 编译 运行程序 1 2 初识输入输出 1 3 注释简介 1 4 控制流 1 4 1 while 语句 1 4 2 for语句 1 4 3 读取数量不定的输入数据 1 4
  • 【Python】赋值、浅拷贝与深拷贝(附图解)

    Python 赋值 浅拷贝与深拷贝 附图解 Python的变量 可变对象与不可变对象 可变对象 不可变对象 赋值 浅拷贝与深拷贝的区别 可变对象的赋值 浅拷贝与深拷贝 赋值 浅拷贝 深拷贝 不可变对象的赋值 浅拷贝与深拷贝 结论 Pytho
  • xml文件修改后,git提交,变更列表中没有xml文件

    小编通过ctrl shift R找到需要修改的xml文件 修改后git提交 变更列表中没有 经过同事提醒 发现自己修改的是编译的xml文件 所以git提交 变更列表中没有xml文件 解决方法 找到Dao层下的xml文件进行修改 git提交变
  • matlab空间马尔可夫链式,基于MATLAB操作的马尔可夫链蒙特卡罗方法(MCMC)

    1 Sampling from Random Variables 4 1 1 Standard distributions 4 1 2 Sampling from non standard distributions 7 1 2 1 Inv
  • 边缘云与中心云_云与边缘的工业制造困境

    边缘云与中心云 Typically Deep Learning the subspecies of AI application that have gained the spotlight in the past few years th
  • *SVN从服务器新建本地库2021-10-18

    SVN从服务器新建本地库 1 如图打开版本库浏览器 2 在右侧空白处新建文件夹 3 选中文件夹右键检出 后续按照提示选择自己指定的本地文件夹位置即可 后面就可以跟服务器上传和下拉了
  • 20180726:Mac中文件.DS_store的隐藏与开启

    简介 DS store是存储文件夹属性的文件 1 开启 打开终端 键入命令 defaults write com apple finder AppleShowAllFiles YES defaults write com apple fin
  • ref 在 React 中的使用方法和说明

    react标签中ref的写法在 React 中 ref 属性用于引用组件中的某个元素或组件实例 以便在需要时对其进行操作 ref 属性的应用场景很多 比如直接访问 DOM 节点 管理 focus 状态 嵌套子组件等等 下面 我们来详细了解一
  • 递归求逆序

    Description 输入多行文字 输出其逆序 Input 多个文字 Output 其逆序 Sample Input 1 abcd wdwe Sample Output 1 ewdw dcba Hint int main recursiv
  • Qt5自定义状态栏QStatusBar外观(背景)和状态栏基本用法(显示普通消息、临时消息、永久消息)

    本文主要总结Qt状态栏QSatatuBar用法 通过继承状态栏 自定义状态栏背景图形 以及状态栏三种基本用法 状态栏类QStatusBar主要有显示普通消息 显示定时消息 显示永久消息三种功能 三种都十分常用 下面先总结自定义状态栏外观用法
  • 【JavaScript】正则表达式 VS 正规式

    在看JS之前没有怎么接触过正则表达式 只是知道有这么个东西 而在软考学习的时候 在编译原理这块有一个正规式 当时只知道这两个东西不是一个概念 具体哪里不同不太清楚 现在正好学到这里了 在此对比总结一下 一 正规式 一种表示正规集的工具 正规
  • 飞马D2000 激光雷达LVX数据文件解析

    解析出来的结果如下图
  • LVGL V9.0基于VS2022仿真搭建(2)

    完整Demo lvgl lvgl drivers相关资料下载 链接 https pan baidu com s 1h3OKCIBQRX0Hn7KjZsynqg 提取码 sc2l 下载的lv drivers中的win32drv c及win32
  • 云链商城连锁门店新零售O20系统以零售商城

    云链商城连锁门店新零售O20系统以零售商城 门店收银 多渠道进销存 客户管理 互动营销 导购助手 多种奖励模式和数据分析等功能 赋能多品牌连锁门店实现线上线下商品 会员 场景的互联互通 助推企业快速实现营销 服务 效率转型升级 为实体零售企
  • Idea中Java项目修改项目名

    1 修改项目文件夹名称 下面是在Idea中改 也可以直接找到项目文件夹重命名 2 关闭项目 Idea会默认生成原项目名的文件夹 将其删除 3 导入重命名后的项目文件夹 4 导入成功后 在Idea中修改模块名称 大功告成 修改项目名总共有三处
  • 【Java】用do-while循环,实现猜数字。

    package TcmStudy day05 import java util Scanner public class DoWhileText01 public static void main String args Scanner i
  • git revert讲解

    git的工作流 工作区 即自己当前分支所修改的代码 git add xx 之前的 不包括 git add xx 和 git commit xxx 之后的 暂存区 已经 git add xxx 进去 且未 git commit xxx 的 本
  • Pandas基本数据对象及操作

    1 Series 创建Series import pandas as pd countries 中国 美国 澳大利亚 countries s pd Series countries print type countries s print