Python Pandas 对列/行 Column/Row 进行选择,增加,删除操作

2023-11-07

一、列操作

1.1 选择列

d = {'one' : pd.Series([1, 2, 3], index=['a', 'b', 'c']),
   'two' : pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])}

df = pd.DataFrame(d)
print (df ['one'])
# 选择其中一列进行显示,列长度为最长列的长度
# 除了 index 和 数据,还会显示 列表头名,和 数据 类型

运行结果:

a    1.0
b    2.0
c    3.0
d    NaN
Name: one, dtype: float64

1.2 增加列

d = {'one' : pd.Series([1, 2, 3], index=['a', 'b', 'c']),
   'two' : pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])}

df = pd.DataFrame(d)

# Adding a new column to an existing DataFrame object with column label by passing new series

print ("Adding a new column by passing as Series:")
df['three']=pd.Series([10,30,20],index=['a','c','b'])
print(df)
# 增加列后进行显示,其中 index 用于对应到该列 元素 位置(所以位置可以不由 列表 中的顺序进行指定)

print ("Adding a new column using the existing columns in DataFrame:")
df['four']=df['one']+df['two']+df['three']
print(df)
# 我们选定列后,直接可以对整个列的元素进行批量运算操作,这里 NaN 与其他元素相加后,还是 NaN

运行结果:

Adding a new column by passing as Series:
   one  two  three
a  1.0    1   10.0
b  2.0    2   20.0
c  3.0    3   30.0
d  NaN    4    NaN
Adding a new column using the existing columns in DataFrame:
   one  two  three  four
a  1.0    1   10.0  12.0
b  2.0    2   20.0  24.0
c  3.0    3   30.0  36.0
d  NaN    4    NaN   NaN

1.3 删除列(del 和 pop 函数)

d = {'one' : pd.Series([1, 2, 3], index=['a', 'b', 'c']),
   'two' : pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd']),
   'three' : pd.Series([10,20,30], index=['a','b','c'])}

df = pd.DataFrame(d)
print ("Our dataframe is:")
print(df)

# 使用 del 函数
print ("Deleting the first column using DEL function:")
del(df['one'])
print(df)

# 使用 pop 函数
print ("Deleting another column using POP function:")
df_2=df.pop('two') # 将一列 pop 到新的 dataframe
print(df_2)
print(df)

运行结果:

Our dataframe is:
   one  two  three
a  1.0    1   10.0
b  2.0    2   20.0
c  3.0    3   30.0
d  NaN    4    NaN
Deleting the first column using DEL function:
   two  three
a    1   10.0
b    2   20.0
c    3   30.0
d    4    NaN
Deleting another column using POP function:
   three
a   10.0
b   20.0
c   30.0
d    NaN
POP column:
a    1
b    2
c    3
d    4
Name: two, dtype: int64

二、行操作

2.1 选择行

2.1.1 通过 label 选择行(loc 函数)

d = {'one' : pd.Series([1, 2, 3], index=['a', 'b', 'c']),
   'two' : pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])}

df = pd.DataFrame(d)
print(df.loc['b']) # 显示这一行中,对应表头 下的 对应数据,同时显示 行 index 和 数据类型

运行结果:

one    2.0
two    2.0
Name: b, dtype: float64

2.1.2 通过序号选择行(iloc 函数)

d = {'one' : pd.Series([1, 2, 3], index=['a', 'b', 'c']),
   'two' : pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])}

df = pd.DataFrame(d)
print(df.iloc[2]) # 序号 2 对应的是第 3 行的数据

运行结果:

one    3.0
two    3.0
Name: c, dtype: float64

2.1.3 通过序号选择行切片

d = {'one' : pd.Series([1, 2, 3], index=['a', 'b', 'c']),
   'two' : pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])}

df = pd.DataFrame(d)
print(df[2:4]) # 这里选择第 3 到 第 4 行,与 Python 切片一致,不需要函数,直接切片即可

运行结果:

   one  two
c  3.0    3
d  NaN    4

2.2 增加行(append 函数)

# 通过 append 函数
df = pd.DataFrame([[1, 2], [3, 4]], columns = ['a','b'])
df2 = pd.DataFrame([[5, 6], [7, 8]], columns = ['a','b'])

df = df.append(df2)
print(df) # 这里相当于把 第二个 dataframe 与第一个进行拼接,默认的 index 都是 0 1
print(df.loc[0]) # 这里有两行的 index 是 0

运行结果:

   a  b
0  1  2
1  3  4
0  5  6
1  7  8
   a  b
0  1  2
0  5  6

2.3 删除行(drop 函数)

# 通过 drop 函数
df = pd.DataFrame([[1, 2], [3, 4]], columns = ['a','b'])
df2 = pd.DataFrame([[5, 6], [7, 8]], columns = ['a','b'])

df = df.append(df2)

df = df.drop(0) # 这里有两个行标签为 0,所以直接删除了 2 行
print(df)

运行结果:

   a  b
1  3  4
1  7  8
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Python Pandas 对列/行 Column/Row 进行选择,增加,删除操作 的相关文章

随机推荐

  • windows7在无法访问Internet的情况下,修改公共网络为家庭网络(或工作网络)

    打开网络共享中心 可以看到此时无法连接Internet 打开计算机 点击网络 单击更改 启用网络发现和文件共享 选择 否 使已连接的网络成为专用网络 重新打开网络和共享中心 一定要关闭后重新打开 可以看到原本的公共网络已经变成了工作网络 注
  • 自动驾驶的算力(TOPS)谎言

    原文链接 当前 自动驾驶运算系统正在进入一场算力的竞赛中 特斯拉刚以自研的达到72TOPS算力 业内最强的FSD HW3 0升级HW2 5不久 英伟达最新推出的芯片系统达到了2000TOPS的惊人算力 然而 自动驾驶首要确保的安全性和算力并
  • ffmpeg使用NVIDIA Jeston Xavier NX 硬编码

    一 需求 NX的板子外接相机 使用opencv从共享内存中取图 转化成Mat 之后利用ffmpeg进行h264编码 然后推送到rtmp服务器 开始使用cpu软编码 占用cpu在150 左右 先改用GPU的 NVENC芯片进行硬编码 cpu占
  • 请体验一下falcon 180b 大语言模型的感觉

    引言 由Technology Innovation Institute T四训练的开源大模型Falcon 180B登陆Hugging Face Falcon180B为开源大模型树立了全新的标杆 作为当前最大的开源大模型 有l80B参数并且是
  • set()函数 c++用法

    SET 是一种包含已排序对象的关联容器 set集合容器实现了红黑树 Red Black Tree 的平衡二叉检索树的数据结构 在插入元素时 它会自动调整二叉树的排列 把元素放到适当的位置 它不会插入相同键值的元素 而采取忽略处理 平衡二叉树
  • SIM卡工作原理

    1 如何检测卡的插入 参考文献 1 https blog csdn net LUOHUATINGYUSHENG article details 96473340 2 如何判断SIM卡的工作电压 包括1 8V 3V 5V 判断逻辑 模块先给s
  • Linux安装nginx/tenginx

    tenginx为例 Tengine2 3 3点击下载 先安装依赖库 Ubuntu为例 PCRE库支持正则表达式 sudo apt get install libpcre3 libpcre3 dev zlib库用于对HTTP包的内容做gzip
  • 1.basic_something

    1 基础必须 4个 op session graph run 矩阵乘法 tf matmul import tensorflow as tf m1 tf constant 3 3 定义1行2列的矩阵常量op 1 op m2 tf consta
  • UE4_c++ 设置Actor BeginPlay的顺序

    在项目开发中 涉及到数据初始化 一个类可能需要依赖另一个类的初始化 因此在某些时候 需要把一个类的初始化的优先级提高 针对不同Actor的BeginPlay在运行时的执行顺序 有兴趣的可以自行去测试 意义不大 下面提供一种方法 使一个Act
  • Python图像锐化及边缘检测(Roberts、Prewitt、Sobel、Lapllacian、Canny、LOG)

    目录 图像锐化概述 算法方法介绍 代码实现 效果展示 图像锐化概述 图像锐化 image sharpening 是补偿图像的轮廓 增强图像的边缘及灰度跳变的部分 使图像变得清晰 分为空间域处理和频域处理两类 图像锐化是为了突出图像上地物的边
  • 睿智的目标检测51——Tensorflow2搭建yolo3目标检测平台

    睿智的目标检测51 Tensorflow2搭建yolo3目标检测平台 学习前言 源码下载 YoloV3实现思路 一 整体结构解析 二 网络结构解析 1 主干网络Darknet53介绍 2 构建FPN特征金字塔进行加强特征提取 3 利用Yol
  • java try的用法_Java中try、catch的使用方法

    Java中有两种处理异常的方式 分别是用throws抛出异常 用try catch捕获异常 try catch 在Java try catch语句的语法格式 try 代码块 catch Exception1 e 抛出异常后所要进行的操作 当
  • ElasticSearch最佳入门实践(五十八)搜索相关参数梳理以及bouncing results问题解决方案

    1 preference 决定了哪些shard会被用来执行搜索操作 primary primary first local only node xyz prefer node xyz shards 2 3 bouncing results问
  • 如何在SQL查询中文列

    背景介绍 需求背景 第三方提供视图 查询该视图信息 列名采取中文形式 例如 视图名V Test 姓名 性别 工作年限 年 张三 男 4 李四 女 1 复现步骤 Navicat配置Sql Server 因为未接触过中文列名 所以简单查了下 可
  • 如何向icloud上传文件_怎么把文件放进苹果icloud

    展开全部 将文件放入苹果62616964757a686964616fe58685e5aeb931333365653932iCloud的方法很多 介绍以下三种方法供参考 方法一 手机 通过苹果手机直接存储到iCloud 1 在苹果应用商店 A
  • kali 远程登陆提示 拒绝访问(access denied)

    1 今天配置kali远程登陆 配置好后登陆发现输入密码对的 但是还是拒绝访问 access denied 2 后来发现是配置在 etc ssh sshd config 时候 配错了 把 PermitRootLogin without pas
  • ⛳ Class.forName()方法

    目录 Class forName 方法 特点 举例 Class forName 方法 Class forName 是Java中的一个反射方法 用于根据类的完整限定名 fully qualified name 加载类并返回对应的Class对象
  • 调整数组顺序使奇数位于偶数前面(java)

    一 问题描述 输入一个整数数组 实现一个函数来调整该数组中数字的顺序 使得所有的奇数位于数组的前半部分 所有的偶数位于位于数组的后半部分 并保证奇数和奇数 偶数和偶数之间的相对位置不变 二 算法分析 给定一个数组array 目标 调整数组中
  • java 枚举类使用反射

    目录 前言 一 枚举类 二 反射获取枚举 三 反射调用枚举方法 前言 跟普通类使用反射基本一样 一 枚举类 public enum OperateType add 添加 0 delete 删除 1 select 查询 2 update 修改
  • Python Pandas 对列/行 Column/Row 进行选择,增加,删除操作

    Pandas 的列 行操作 一 列操作 1 1 选择列 1 2 增加列 1 3 删除列 del 和 pop 函数 二 行操作 2 1 选择行 2 1 1 通过 label 选择行 loc 函数 2 1 2 通过序号选择行 iloc 函数 2