String Manipulation related with pandas

String object Methods

import pandas as pd
import numpy as np
val='a,b, guido'
val.split(',') # normal python built-in method split
['a', 'b', ' guido']
pieces=[x.strip() for x in val.split(',')];pieces  # strip whitespace
['a', 'b', 'guido']
'::'.join(pieces)
'a::b::guido'
val.count(',')
2
val.count('guido')
1
val.replace(',',':')
'a:b: guido'
val.swapcase()
'A,B, GUIDO'
val[::-1]
'odiug ,b,a'

Regular expression

The re module functions fall into 3 categories:pattern matching,substitution,splliting.

import re
text='foo   bar\t baz  \t qux'
re.split('\s+',text)
['foo', 'bar', 'baz', 'qux']
regex=re.compile('\s+')
regex.split(text)
['foo', 'bar', 'baz', 'qux']
regex.findall(text)
['   ', '\t ', '  \t ']
  • To avoid unwanted escaping with \ in a regular expression,use raw string literals
text="""Dave dave@google.com
Steve steve@mail.com
Rob rob@mail.com
Ryan ryan@yahoo.com
"""
pattern=r'[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}'
regex=re.compile(pattern,re.I)

Using findall() produces a list of the email address.

regex.findall(text)
['dave@google.com', 'steve@mail.com', 'rob@mail.com', 'ryan@yahoo.com']
regex.findall(r' J.onepy+@w-m.co')
['J.onepy+@w-m.co']

search() returns a specified match object for the first email address in the text.

m=regex.search(text)
m
<re.Match object; span=(5, 20), match='dave@google.com'>
regex.match(text)
text[m.start():m.end()]
'dave@google.com'

regex.match(text) returns None,as it onlyu will match if the pattern occurs at the start of the string.

sub() will return a new string with occurences of the pattern replaced by a new string.

print(regex.sub('READACTED',text))
Dave READACTED
Steve READACTED
Rob READACTED
Ryan READACTED

Vectorized string functions in pandas

data={'Dave':'dave@google.com','Steve':'steve@gmeil.com','Rob':'rob@gmail.com','Wes':np.nan}
data=pd.Series(data);data
Dave     dave@google.com
Steve steve@gmeil.com
Rob rob@gmail.com
Wes NaN
dtype: object
data.isnull()
Dave     False
Steve False
Rob False
Wes True
dtype: bool
data.str.contains('gmail')
Dave     False
Steve False
Rob True
Wes NaN
dtype: object
data
Dave     dave@google.com
Steve steve@gmeil.com
Rob rob@gmail.com
Wes NaN
dtype: object
data.map(lambda x:x[:2],na_action='ignore')  # x is the value in data, the returned Series has the same index with caller,data here.
Dave      da
Steve st
Rob ro
Wes NaN
dtype: object
help(data.map)
Help on method map in module pandas.core.series:

map(arg, na_action=None) method of pandas.core.series.Series instance
Map values of Series using input correspondence (a dict, Series, or
function). Parameters
----------
arg : function, dict, or Series
Mapping correspondence.
na_action : {None, 'ignore'}
If 'ignore', propagate NA values, without passing them to the
mapping correspondence. Returns
-------
y : Series
Same index as caller. Examples
-------- Map inputs to outputs (both of type `Series`): >>> x = pd.Series([1,2,3], index=['one', 'two', 'three'])
>>> x
one 1
two 2
three 3
dtype: int64 >>> y = pd.Series(['foo', 'bar', 'baz'], index=[1,2,3])
>>> y
1 foo
2 bar
3 baz >>> x.map(y)
one foo
two bar
three baz If `arg` is a dictionary, return a new Series with values converted
according to the dictionary's mapping: >>> z = {1: 'A', 2: 'B', 3: 'C'} >>> x.map(z)
one A
two B
three C Use na_action to control whether NA values are affected by the mapping
function. >>> s = pd.Series([1, 2, 3, np.nan]) >>> s2 = s.map('this is a string {}'.format, na_action=None)
0 this is a string 1.0
1 this is a string 2.0
2 this is a string 3.0
3 this is a string nan
dtype: object >>> s3 = s.map('this is a string {}'.format, na_action='ignore')
0 this is a string 1.0
1 this is a string 2.0
2 this is a string 3.0
3 NaN
dtype: object See Also
--------
Series.apply : For applying more complex functions on a Series.
DataFrame.apply : Apply a function row-/column-wise.
DataFrame.applymap : Apply a function elementwise on a whole DataFrame. Notes
-----
When `arg` is a dictionary, values in Series that are not in the
dictionary (as keys) are converted to ``NaN``. However, if the
dictionary is a ``dict`` subclass that defines ``__missing__`` (i.e.
provides a method for default values), then this default is used
rather than ``NaN``: >>> from collections import Counter
>>> counter = Counter()
>>> counter['bar'] += 1
>>> y.map(counter)
1 0
2 1
3 0
dtype: int64
pattern
'[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}'
data.str.findall(pattern,flags=re.I)
Dave     [dave@google.com]
Steve [steve@gmeil.com]
Rob [rob@gmail.com]
Wes NaN
dtype: object
matches=data.str.match(pattern,flags=re.I);matches
Dave     True
Steve True
Rob True
Wes NaN
dtype: object
matches.str.get(1)
Dave    NaN
Steve NaN
Rob NaN
Wes NaN
dtype: float64
matches.str[0]
Dave    NaN
Steve NaN
Rob NaN
Wes NaN
dtype: float64
data.str[:5]
Dave     dave@
Steve steve
Rob rob@g
Wes NaN
dtype: object

String Manipulation related with pandas的更多相关文章

  1. VK Cup 2012 Qualification Round 2 C. String Manipulation 1.0 字符串模拟

    C. String Manipulation 1.0 Time Limit: 20 Sec Memory Limit: 256 MB 题目连接 codeforces.com/problemset/pr ...

  2. Bash String Manipulation Examples – Length, Substring, Find and Replace--reference

    In bash shell, when you use a dollar sign followed by a variable name, shell expands the variable wi ...

  3. string manipulation in game development-C # in Unity -

    ◇ string manipulation in game development-C # in Unity - It is about the various string ● defined as ...

  4. CodeForces 159c String Manipulation 1.0

    String Manipulation 1.0 Time Limit: 3000ms Memory Limit: 262144KB This problem will be judged on Cod ...

  5. leetcode@ [68] Text Justification (String Manipulation)

    https://leetcode.com/problems/text-justification/ Given an array of words and a length L, format the ...

  6. [IoLanguage]Io Programming Guide[转]

    Io Programming Guide     Introduction Perspective Getting Started Downloading Installing Binaries Ru ...

  7. pandas 之 数据清洗-缺失值

    Abstract During the course fo doing data analysis and modeling, a significant amount of time is spen ...

  8. [转帖]Introduction to text manipulation on UNIX-based systems

    Introduction to text manipulation on UNIX-based systems https://www.ibm.com/developerworks/aix/libra ...

  9. Pandas 之 DataFrame 常用操作

    import numpy as np import pandas as pd This section will walk you(引导你) through the fundamental(基本的) ...

  10. Java String Class Example--reference

    reference:http://examples.javacodegeeks.com/core-java/lang/string/java-string-class-example/ 1. Intr ...

随机推荐

  1. 八米云-各种小主机x86系统-小白保姆式超详细刷机教程

    疑难解答加微信机器人,给它发:进群,会拉你进入八米交流群 机器人微信号:bamibot 简洁版教程访问:https://bbs.8miyun.cn 准备工作 说明: 1.小节点X86 单线500M以下 ...

  2. MybatisPlus - [02] HelloWorld

    参考:https://www.cnblogs.com/haoxinyue/p/5208136.html(分布式系统唯一ID生成方案汇总) 一.准备工作 (1)创建数据库: create databas ...

  3. Flink - [02] 安装部署(Standalone)

    一.准备 1.角色规划 Flink Standalone 角色规划 节点名称 node01 node02 node03 master ○     worker   ○ ○ zookeeper ○ ○ ...

  4. Ansible - [03] Ansible ad-hoc模式

    Ansible ad-hoc是一种通过命令行批量管理的方式 格式:ansible 主机集合 -m 模块名 -a "参数" 其他参数: -k 使用密码远程.-i 指定主机列表文件 以 ...

  5. K8s - 容器编排引擎Kubernetes

    什么是Kubernetes? 背景 Kubernetes 是开源的容器集群管理项目,诞生于2014年,由Google公司发起 前身Borg系统在Google内部应用了十几年,积累了大量来自生产环境的实 ...

  6. Win10打开IE自动跳转至Edge解决办法

    WIN + R输入inetcpl.cpl弹出Internet属性对话窗口 点击上面菜单中的[高级]选项 滑动右侧滚动条,找到[浏览]项下面的[启用第三方浏览器拓展*]并取消勾选 双击IE浏览器图标测试 ...

  7. swoole(7)php进程间通信-消息队列

    php实现消息队列操作 ftok:可以将一个路径转换成消息队列可用的key值 msg_get_queue:第一个参数是消息队列的key 第二个参数是消息队列的读写权限 server代码: <?p ...

  8. php框架里面数组合并的方法

    php框架里面用call_user_func_array(array($dispatch, $actionName), $param);传参的时候,接收的$actionName方法不能接收数组参数. ...

  9. 提示词工程——AI应用必不可少的技术

    引言 在人工智能技术飞速发展的今天,大语言模型(LLM)已成为推动技术革新的核心引擎.然而,如何让这些"聪明"的模型真正落地业务场景.解决实际问题?答案往往不在于模型本身的参数规模 ...

  10. 原生JS实现虚拟列表(不使用Vue,React等前端框架)

    好家伙,   1. 什么是虚拟列表 虚拟列表(Virtual List)是一种优化长列表渲染性能的技术.当我们需要展示成千上万条数据时,如果一次性将所有数据渲染到DOM中,会导致页面卡顿甚至崩溃.虚拟 ...