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

参考链接: 修剪Java中的字符串(删除前导和尾随空格)

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

 

  

   

    

     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类:  

     Splitting 分裂 Stripping 剥离 Replacing 更换 Filtering 筛选 Combining 结合 

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

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

     import numpy as npimport 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

     

      

       

        

         

          

         

        

       

      

     

      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

     

      

       

        

         

          

         

        

       

      

     

     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)

     

      

       

        

         

          

         

        

       

      

     

      拆分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:

      考虑以下系列:  

     

      

       

        

         

          

         

        

       

      

     

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

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

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

     

      

       

        

         

          

         

        

       

      

     

     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)

     

      

       

        

         

          

         

        

       

      

     

     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”。  

     

      

       

        

         

          

         

        

       

      

     

     Those leading and trailing spaces can be removed with strip:

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

     df_sample['col_d'] = df_sample['col_d'].str.strip()

     

      

       

        

         

          

         

        

       

      

     

    

   

  

  

   

    

      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')

     

      

       

        

         

          

         

        

       

      

     

    

   

  

  

   

    

      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:

      这是我们的原始数据框:  

     

      

       

        

         

          

         

        

       

      

     

     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')]

     

      

       

        

         

          

         

        

       

      

     

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

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

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

     

      

       

        

         

          

         

        

       

      

     

     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]

     

      

       

        

         

          

         

        

       

      

     

     upper  = df_sample['col_b'].str[-3:-1]

     

      

       

        

         

          

         

        

       

      

     

    

   

  

  

   

    

      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

     

      

       

        

         

          

         

        

       

      

     

    

   

  

  

   

    

      奖励:对象与字符串 (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参数,以传递给字符串数据类型。  

     

      

       

        

         

          

         

        

       

      

     

    

   

  

  

   

    

     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/540196.shtml

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

相关文章

更改域控制器的计算机名

林功能级别必须为Windows Server 2003及以上 1. netdom computername Server08-1.contoso.com /add:08Server1.contoso.com 2. netdom computername Server08-1.contoso.com /makeprimary:08Server1.contoso.com 3. Restart your computer 4. netdom computername 08Server1.co…

[转载] Google Java代码规范

参考链接: 使用Java计算文本文件txt中的行数/单词数/字符数和段落数 原文地址:https://google.github.io/styleguide/javaguide.html GIthub上GoogleCode风格的配置文件(支持Eclipse IDE和IntelliJ IDE):https://git…

SQL PASS西雅图之行——签证篇

本人有幸通过IT168&itpub的站庆活动http://www.itpub.net/thread-1716961-1-1.html,并应微软邀请参加了在西雅图举办的The Conference for SQL Server Professionals(简称SQL-PASS)。 SQL-PASS会议计划于2012年11月6日-9日举行&#xff0…

[转载] java8 lambda表达式 List转为Map

参考链接&#xff1a; 使用Lambda表达式检查字符串在Java中是否仅包含字母 public static void main(String[] args) { List<User> userList new ArrayList<User>(); User user0 new User("han1", "男1", 20); User user1 new User("…

11.python并发入门(part5 event对象)

一、引入event。 每个线程&#xff0c;都是一个独立运行的个体&#xff0c;并且每个线程的运行状态是无法预测的。 如果一个程序中有很多个线程&#xff0c;程序的其他线程需要判断某个线程的运行状态&#xff0c;来确定自己下一步要执行哪些操作。 threading模块中的event对象…

[转载] Java 将字符串首字母转为大写 - 利用ASCII码偏移

参考链接&#xff1a; 使用ASCII值检查Java中的字符串是否仅包含字母 将字符串name 转化为首字母大写。普遍的做法是用subString()取第一个字母转成大写再与之后的拼接&#xff1a; str str.substring(0, 1).toUpperCase() str.substring(1); 看到一种效率更高的做法&…

俞永福卸任阿里大文娱董事长,改任 eWTP 投资组长

两天前&#xff08;11月13日&#xff09;&#xff0c;阿里文娱董事长俞永福离职的消息&#xff0c;在互联网圈炸了锅。但很快&#xff0c;俞本人就在微博做了澄清&#xff0c;并称“永远幸福&#xff0c;我不会离开”。然而就在今天&#xff08;11月15日&#xff09;&#xff0…

[转载] java提取字符串中的字母数字

参考链接&#xff1a; 使用Regex检查字符串在Java中是否仅包含字母 String str "adsf adS DFASFSADF阿德斯防守对方asdfsadf37《&#xff1f;&#xff1a;&#xff1f;%#&#xffe5;%#&#xffe5;%#$%#$%^><?1234"; str str.replaceAll("[^a-zA-…

snort的详细配置

前一段一直在做snort入侵检测系统的安装以及配置&#xff0c;看了很多的网上资料&#xff0c;也算是总结了下前辈的经验吧。需要的软件包&#xff1a;1、httpd-2.2.6.tar.gz2、mysql-5.1.22-rc-linux-i686-icc-glibc23.tar.gz3、php-5.2.4.tar.bz24、acid-0.9.6b23.tar.gz5、ad…

[转载] Java:获取数组中的子数组的多种方法

参考链接&#xff1a; Java中的数组Array 我的个人博客&#xff1a;zhang0peter的个人博客 Java&#xff1a;从一个数组中创建子数组 使用Arrays.copyOfRange函数 Arrays.copyOfRange支持&#xff1a;boolean[]&#xff0c; byte[] &#xff0c;char[]&#xff0c;double…

[转载] Java中Array(数组)转List(集合类)的几种方法

参考链接&#xff1a; Java中的数组类Array 1、循环。新建List类&#xff0c;循环填充。 2、利用Arrays类的静态方法asList()。 Arrays.asList(T[])返回Arrays类的一个内部内List(T)&#xff0c;此类继承自AbstractList&#xff0c;不可增删。若想要一个可以增删的List类&am…

Linux查看系统cpu个数、核心书、线程数

Linux查看系统cpu个数、核心书、线程数 现在cpu核心数、线程数越来越高&#xff0c;本文将带你了解如何确定一台服务器有多少个cpu、每个cpu有几个核心、每个核心有几个线程。 查看物理cpu个数 cat /proc/cpuinfo |grep "physical id"|sort |uniq|wc -l 查看核…

[转载] java中数组的反射的探究

参考链接&#xff1a; Java中的反射数组类reflect.Array 数组的反射有什么用呢&#xff1f;何时需要使用数组的反射呢&#xff1f;先来看下下面的代码&#xff1a; Integer[] nums {1, 2, 3, 4}; Object[] objs nums; //这里能自动的将Integer[]转成Object[] Object obj n…

防火墙iptables之常用脚本

防火墙iptables之常用脚本 转自&#xff1a;http://zhujiangtao.blog.51cto.com/6387416/1286490 标签&#xff1a;防火墙 主机 1。不允许别人ping我的主机&#xff0c;但是我可以ping别人的主机 #!/bin/bash iptables -F iptables -X iptables -Z modprobe ip_tables modprobe…

[转载] java中50个关键字以及各自用法大全

参考链接&#xff1a; Java中的默认数组值 关键字和保留字的区别 正确识别java语言的关键字&#xff08;keyword&#xff09;和保留字&#xff08;reserved word&#xff09;是十分重要的。Java的关键字对java的编译器有特殊的意义&#xff0c;他们用来表示一种数据类型&…

NFS 共享存储

服务器客户端yum -y install rpcbind nfs-utils 服务器 vim /etc/exports /data 192.168.10.0/24(rw,sync,no_root_squash) * ro # 只读权限 * rw # 读写权限 * sync # 同步&#xff0c;数据更安全&#xff0c;速度慢 * async #异步&#xff0c;速度快&#xff0c;效率高&a…

[转载] Java中的final变量、final方法和final类

参考链接&#xff1a; Java中的final数组 &#xff5c; Final arrays 1、final变量 final关键字可用于变量声明&#xff0c;一旦该变量被设定&#xff0c;就不可以再改变该变量的值。通常&#xff0c;由final定义的变量为常量。例如&#xff0c;在类中定义PI值&#xff0c;可…

Linux基础篇_01_计算机概论

学习资料&#xff1a;《鸟哥的Linux私房菜&#xff08;基础篇&#xff09;》部分&#xff1a;Linux的规划与安装 时间&#xff1a;20130225 学习笔记&#xff1a;计算机定义&#xff1a;接受使用者输入指令与数据&#xff0c; 经由中央处理器的数学与逻辑单元运算处理后&#x…

[转载] java中的经典问题:传值与传引用

参考链接&#xff1a; 有关Java中数组分配的有趣事实 参数传递的秘密 知道方法参数如何传递吗&#xff1f; 记得刚开始学编程那会儿&#xff0c;老师教导&#xff0c;所谓参数&#xff0c;有形式参数和实际参数之分&#xff0c;参数列表中写的那些东西都叫形式参数&#x…

[3/21]Windows Server 2008时钟方面的改进展示

在Windows Server 2008中的时钟显示和以往Windows Server 2003及以前的版本显示有很大的差别。如果要显示并进行简单的时间修改可以在时钟上双击&#xff0c;会出现如下图所示的界面。在上图中可以调整但无法进行真正的修改&#xff0c;彻底修改需要点击&#xff02;更改日期和…