[轉載] 字符串操作截取后面的字符串_對字符串的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.pswp.cn/news/540196.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/540196.shtml
英文地址,請注明出處:http://en.pswp.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;更改日期和…