字符串操作截取后面的字符串_对字符串的5个必知的熊猫操作

字符串操作截取后面的字符串

We have to represent every bit of data in numerical values to be processed and analyzed by machine learning and deep learning models. However, strings do not usually come in a nice and clean format and require preprocessing to convert to numerical values. Pandas offers many versatile functions to modify and process string data efficiently.

我们必须以数值表示数据的每一位,以便通过机器学习和深度学习模型进行处理和分析。 但是,字符串通常不会采用简洁的格式,需要进行预处理才能转换为数值。 熊猫提供了许多通用功能,可以有效地修改和处理字符串数据。

In this post, we will discover how Pandas can manipulate strings. I grouped string functions and methods under 5 categories:

在本文中,我们将发现Pandas如何操纵字符串。 我将字符串函数和方法分为5类:

  1. Splitting

    分裂

  2. Stripping

    剥离

  3. Replacing

    更换

  4. Filtering

    筛选

  5. Combining

    结合

Let’s first create a sample dataframe to work on for examples.

让我们首先创建一个示例数据框以进行示例。

import numpy as np
import pandas as pdsample = {
'col_a':['Houston,TX', 'Dallas,TX', 'Chicago,IL', 'Phoenix,AZ', 'San Diego,CA'],
'col_b':['$64K-$72K', '$62K-$70K', '$69K-$76K', '$62K-$72K', '$71K-$78K' ],
'col_c':['A','B','A','a','c'],
'col_d':[' 1x', ' 1y', '2x ', '1x', '1y ']
}df_sample = pd.DataFrame(sample)
df_sample
Image for post

1.分裂 (1. Splitting)

Sometimes strings carry more than one piece of information and we may need to use them separately. For instance, “col_a” contains both city and state. The split function of pandas is a highly flexible function to split strings.

有时字符串包含不止一条信息,我们可能需要单独使用它们。 例如,“ col_a”包含城市和州。 pandas的split函数是用于拆分字符串的高度灵活的函数。

df_sample['col_a'].str.split(',')0      [Houston, TX] 
1 [Dallas, TX]
2 [Chicago, IL]
3 [Phoenix, AZ]
4 [San Diego, CA]
Name: col_a, dtype: object

Now each element is converted to a list based on the character used for splitting. We can easily export individual elements from those lists. Let’s create a “state” column.

现在,每个元素都会根据用于拆分的字符转换为列表。 我们可以轻松地从这些列表中导出单个元素。 让我们创建一个“状态”列。

df_sample['state'] = df_sample['col_a'].str.split(',').str[1]df_sample
Image for post

Warning: Subscript ([1]) must be applied with str keyword. Otherwise, we will get the list in the specified row.

警告 :下标([1])必须与str关键字一起应用。 否则,我们将在指定的行中获取列表。

df_sample['col_a'].str.split(',')[1]
['Dallas', 'TX']

The splitting can be done on any character or letter.

可以对任何字符或字母进行拆分。

The split function returns a dataframe if expand parameter is set as True.

如果将expand参数设置为True,则split函数将返回一个数据帧。

df_sample['col_a'].str.split('a', expand=True)
Image for post

拆分vs rsplit (split vs rsplit)

By default, splitting is done from the left. To do splitting on the right, use rsplit.

默认情况下,拆分是从左侧开始的。 要在右侧进行拆分,请使用rsplit

Consider the series below:

考虑以下系列:

Image for post

Let’s apply split function and limit the number of splits with n parameter:

让我们应用split函数并使用n参数限制拆分次数:

categories.str.split('-', expand=True, n=2)
Image for post

Only 2 splits on the left are performed. If we do the same operation with rsplit:

左侧仅执行2个拆分。 如果我们对rsplit执行相同的操作:

categories.str.rsplit('-', expand=True, n=2)
Image for post

Same operation is done but on the right.

完成相同的操作,但在右侧。

2.剥离 (2. Stripping)

Stripping is like trimming tree branches. We can remove spaces or any other characters at the beginning or end of a string.

剥离就像修剪树枝。 我们可以删除字符串开头或结尾的空格或任何其他字符。

For instance, the strings in “col_b” has $ character at the beginning which can be removed with lstrip:

例如,“ col_b”中的字符串开头有$字符,可以使用lstrip将其删除:

df_sample['col_b'].str.lstrip('$')0    64K-$72K 
1 62K-$70K
2 69K-$76K
3 62K-$72K
4 71K-$78K
Name: col_b, dtype: object

Similary, rstrip is used to trim off characters from the end.

类似地, rstrip用于从末尾修剪字符。

Strings may have spaces at the beginning or end. Consider “col_d” in our dataframe.

字符串的开头或结尾可以有空格。 考虑一下我们数据框中的“ col_d”。

Image for post

Those leading and trailing spaces can be removed with strip:

那些前导和尾随空格可以用strip除去:

df_sample['col_d'] = df_sample['col_d'].str.strip()
Image for post

3.更换 (3. Replacing)

Pandas replace function is used to replace values in rows or columns. Similarly, replace as a string operation is used to replace characters in a string.

熊猫替换功能用于替换行或列中的值。 同样,替换为字符串操作用于替换字符串中的字符。

Let’s replace “x” letters in “col_d” with “z”.

让我们用“ z”替换“ col_d”中的“ x”个字母。

df_sample['col_d'] = df_sample['col_d'].str.replace('x', 'z')
Image for post

4.筛选 (4. Filtering)

We can filter strings based on the first and last characters. The functions to use are startswith() and endswith().

我们可以根据第一个和最后一个字符来过滤字符串。 要使用的函数是startswith()endswith()

Here is our original dataframe:

这是我们的原始数据框:

Image for post

Here is a filtered version that only includes rows in which “col_a” ends with the letter “x”.

这是一个过滤的版本,仅包含“ col_a”以字母“ x”结尾的行。

df_sample[df_sample['col_a'].str.endswith('X')]
Image for post

Or, rows in which “col_b” starts with “$6”:

或者,其中“ col_b”以“ $ 6”开头的行:

df_sample[df_sample['col_b'].str.startswith('$6')]
Image for post

We can also filter strings by extracting certain characters. For instace, we can get the first 2 character of strings in a column or series by str[:2].

我们还可以通过提取某些字符来过滤字符串。 对于instace,我们可以通过str [:2]获得列或系列中字符串的前2个字符。

“col_b” represents a value range but numerical values are hidden in a string. Let’s extract them with string subscripts:

“ col_b”表示值范围,但数值隐藏在字符串中。 让我们用字符串下标提取它们:

lower  = df_sample['col_b'].str[1:3]
Image for post
upper  = df_sample['col_b'].str[-3:-1]
Image for post

5.结合 (5. Combining)

Cat function can be used to concatenate strings.

Cat函数可用于连接字符串。

We need pass an argument to put between concatenated strings using sep parameter. By default, cat ignores missing values but we can also specify how to handle them using na_rep parameter.

我们需要传递一个参数,以使用sep参数在串联字符串之间放置。 默认情况下,cat会忽略缺失值,但我们也可以使用na_rep参数指定如何处理它们。

Let’s create a new column by concatenating “col_c” and “col_d” with “-” separator.

让我们通过将“ col_c”和“ col_d”与“-”分隔符连接起来创建一个新列。

df_sample['new']=df_sample['col_c'].str.cat(df_sample['col_d'], sep='-')df_sample
Image for post

奖励:对象与字符串 (Bonus: Object vs String)

Before pandas 1.0, only “object” datatype was used to store strings which cause some drawbacks because non-string data can also be stored using “object” datatype. Pandas 1.0 introduces a new datatype specific to string data which is StringDtype. As of now, we can still use object or StringDtype to store strings but in the future, we may be required to only use StringDtype.

在pandas 1.0之前,仅使用“对象”数据类型存储字符串,这会带来一些缺点,因为非字符串数据也可以使用“对象”数据类型进行存储。 Pandas 1.0引入了特定于字符串数据的新数据类型StringDtype 。 到目前为止,我们仍然可以使用object或StringDtype来存储字符串,但是在将来,可能需要我们仅使用StringDtype。

One important thing to note here is that object datatype is still the default datatype for strings. To use StringDtype, we need to explicitly state it.

这里要注意的一件事是对象数据类型仍然是字符串的默认数据类型。 要使用StringDtype,我们需要明确声明它。

We can pass “string” or pd.StringDtype() argument to dtype parameter to string datatype.

我们可以将“ string ”或pd.StringDtype()参数传递给dtype参数,以传递给字符串数据类型。

Image for post

Thank you for reading. Please let me know if you have any feedback.

感谢您的阅读。 如果您有任何反馈意见,请告诉我。

翻译自: https://towardsdatascience.com/5-must-know-pandas-operations-on-strings-4f88ca6b8e25

字符串操作截取后面的字符串

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

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

相关文章

最新 Unity3D鼠标滑轮控制物体放大缩小 [

var s 1.0;function Update () {var cube GameObject.Find("Cube");if(Input.GetAxis("Mouse ScrollWheel")){s Input.GetAxis("Mouse ScrollWheel");cube.transform.localScaleVector3(1*s,1*s,1*s);}}

sublime-text3 安装 emmet 插件

下载sublime,http://www.sublimetext.com/ 安装package control :https://packagecontrol.io/ins... 这个地址需要翻墙,访问不了的可以看下图 import urllib.request,os,hashlib; h 6f4c264a24d933ce70df5dedcf1dcaee ebe013ee18cced0ef93d…

数据科学家访谈录 百度网盘_您应该在数据科学访谈中向THEM提问。

数据科学家访谈录 百度网盘A quick search on Medium with the keywords “Data Science Interview” resulted in hundreds of Medium articles to help guide the reader from what concepts are covered to even specific company interviews ranging from Tesla, Walmart, …

unity3d]鼠标点击地面人物自动走动(也包含按键wasdspace控制)

目录(?)[-] 一效果图二大概步骤 创建一个plane设置层为Terrain因为后面要判断是否点击的是这个层准备好人物模型并且将三个脚本拖放到人物上并且将动画文件也拖放好记得看前面提醒哦 ThirdPersonCamera相当于smoothflowThirdPersonController修改版mouseMoveContr鼠标点击人物…

uva 524(Prime Ring Problem UVA - 524 )

dfs练习题,我素数打表的时候ji了&#xff0c;一直没发现实际上是ji*i&#xff0c;以后可记住了。还有最后一行不能有空格。。。昏迷了半天 我的代码(紫书上的算法) #include <bits/stdc.h> using namespace std; int bk[110]; int num[110]; int vis[110]; int n; void d…

Web 开发基础

一、 Web 开发简介 最早的软件都是运行在大型机上的&#xff0c;软件使用者登陆到大型机上去运行软件。后来随着 PC 机的兴起&#xff0c;软件开始主要运行在桌面上&#xff0c;而数据库这样的软件运行在服务器端&#xff0c;这种 Client/Server 模式简称 CS 架构。随着互联网的…

power bi函数_在Power BI中的行上使用聚合函数

power bi函数Aggregate functions are one of the main building blocks in Power BI. Being used explicitly in measures, or implicitly defined by Power BI, there is no single Power BI report which doesn’t use some sort of aggregate functions.聚合功能是Power BI…

关于如何在Python中使用静态、类或抽象方法的权威指南

Python中方法的工作方式 方法是存储在类属性中的函数&#xff0c;你可以用下面这种方式声明和访问一个函数 >>> class Pizza(object):... def __init__(self, size):... self.size size... def get_size(self):... return self.size...>&…

广义估计方程估计方法_广义估计方程简介

广义估计方程估计方法A key assumption underpinning generalized linear models (which linear regression is a type of) is the independence of observations. In longitudinal data this will simply not hold. Observations within an individual (between time points) …

css二

结构性伪类:nth-child(index)系列1.:first-child2.:last-child3.nth-last-child(index)4.only-child :nth-of-type(index)系列1.first-of-type2.last-of-type3.nth-last-type(index)4.only-of-type :not伪类处理导航栏最后一个竖划线a:not(:last-of-type) :empty伪类 选中所有内…

Unity3d鼠标点击屏幕来控制人物的走动

今天呢&#xff0c;我们来一起实现一个在RPG中游戏中十分常见的功能&#xff0c;通过鼠标点击屏幕来控制人物的走动。首先来说一下原理&#xff0c;当我们点击屏幕时&#xff0c;我们按照一定的方法&#xff0c;将屏幕上的二维坐标转化为三维坐标&#xff0c;然后我们从摄像机位…

Java中的ReentrantLock和synchronized两种锁定机制的对比

2019独角兽企业重金招聘Python工程师标准>>> 多线程和并发性并不是什么新内容&#xff0c;但是 Java 语言设计中的创新之一就是&#xff0c;它是第一个直接把跨平台线程模型和正规的内存模型集成到语言中的主流语言。核心类库包含一个 Thread 类&#xff0c;可以用它…

10.15 lzxkj

几天前写的&#xff0c;忘了放了&#xff0c;在此填坑 10月16的题我出的不写题解了 lzxkj 题目背景 众所不周知的是&#xff0c; 酒店之王 xkj 一个经常迷失自我的人 有一天&#xff0c; 当起床铃再一次打响的时候&#xff0c; TA 用 O(1)的时间在 TA 那早就已经生锈的大脑中自…

大数定理 中心极限定理_中心极限定理:直观的遍历

大数定理 中心极限定理One of the most beautiful concepts in statistics and probability is Central Limit Theorem,people often face difficulties in getting a clear understanding of this and the related concepts, I myself struggled understanding this during my…

万恶之源 - Python数据类型二

列表 列表的介绍 列表是python的基础数据类型之一 ,其他编程语言也有类似的数据类型. 比如JS中的数 组, java中的数组等等. 它是以[ ]括起来, 每个元素用 , 隔开而且可以存放各种数据类型: lst [1,a,True,[2,3,4]]列表相比于字符串,不仅可以存放不同的数据类型.而且可…

230. Kth Smallest Element in a BST

Given a binary search tree, write a function kthSmallest to find the kth smallest element in it.Note: You may assume k is always valid, 1 ≤ k ≤ BSTs total elements.Example 1: Input: root [3,1,4,null,2], k 13/ \1 4\2 Output: 1 Example 2: Input: root …

探索性数据分析(EDA)-不要问如何,不要问什么

数据科学 &#xff0c; 机器学习 (Data Science, Machine Learning) This is part 1 in a series of articles guiding the reader through an entire data science project.这是一系列文章的第1部分 &#xff0c;指导读者完成整个数据科学项目。 I am a new writer on Medium…

unity3d 摄像机跟随鼠标和键盘的控制

鼠标控制&#xff1a; using UnityEngine; using System.Collections; public class shubiao : MonoBehaviour { //public Transform firepos; public int Ball30; public int CurBall1; public Rigidbody projectile; public Vector3 point; public float time100f; public…

《必然》九、享受重混盛宴,是每个人的机会

今天说的是《必然》的第七个关键词&#xff0c;过滤Filtering。1我们需要过滤如今有一个问题&#xff0c;弥漫在我们的生活当中&#xff0c;困扰着所有人。那就是“今天我要吃什么呢&#xff1f;”同样的&#xff0c;书店里这么多的书&#xff0c;我要看哪一本呢&#xff1f;网…

IDEA 插件开发入门教程

2019独角兽企业重金招聘Python工程师标准>>> IntelliJ IDEA 是目前最好用的 JAVA 开发 IDE&#xff0c;它本身的功能已经非常强大了&#xff0c;但是每个人的需求不一样&#xff0c;有些需求 IDEA 本身无法满足&#xff0c;于是我们就需要自己开发插件来解决。工欲善…