资讯专栏INFORMATION COLUMN

Pandas之旅(六): 字符串实用方法汇总

高胜山 / 2534人阅读

摘要:有关字符串基本方法大家好,我又回来了之前的几期我们已经简单了解了的基础操作,但是只要涉及到数据,最常见的就是字符串类型,所以很多时候我们其实都在和字符串打交道,所以今天,我会把我自己总结的,有关字符串的常用方法分享给大家,希望能够帮到各位小

有关字符串基本方法

大家好,我又回来了! 之前的几期我们已经简单了解了pandas的基础操作,但是只要涉及到数据,最常见的就是String(字符串)类型,所以很多时候我们其实都在和字符串打交道,所以今天,我会把我自己总结的,有关字符串的常用方法分享给大家,希望能够帮到各位小伙伴~

Split and format
latitude = "37.24N"
longitude = "-115.81W"
"Coordinates {0},{1}".format(latitude,longitude)
>>>   "Coordinates 37.24N,-115.81W"
f"Coordinates {latitude},{longitude}"
>>>"Coordinates 37.24N,-115.81W"
"{0},{1},{2}".format(*("abc"))
>>>"a,b,c"
coord = {"latitude":latitude,"longitude":longitude}
"Coordinates {latitude},{longitude}".format(**coord)
>>>"Coordinates 37.24N,-115.81W"
Access argument" s attribute
class Point:
    def __init__(self,x,y):
        self.x,self.y = x,y
    def __str__(self):
        return "Point({self.x},{self.y})".format(self = self)
    def __repr__(self):
        return f"Point({self.x},{self.y})"
test_point = Point(4,2)
test_point
>>>    Point(4,2)
str(Point(4,2))
>>>"Point(4,2)"
Replace with %s , %r :
" repr() shows the quote {!r}, while str() doesn"t:{!s} ".format("a1","a2")
>>> " repr() shows the quote "a1", while str() doesn"t:a2 "
Align :
"{:<30}".format("left aligned")
>>>"left aligned                  "
"{:>30}".format("right aligned")
>>>"                 right aligned"
"{:^30}".format("centerd")
>>>"           centerd            "
"{:*^30}".format("centerd")
>>>"***********centerd************"
Replace with %x , %o :
"int:{0:d}, hex:{0:x}, oct:{0:o}, bin:{0:b}".format(42)
>>>"int:42, hex:2a, oct:52, bin:101010"
"{:,}".format(12345677)
>>>"12,345,677"
Percentage :
points = 19
total = 22
"Correct answers: {:.2%}".format(points/total)
>>>"Correct answers: 86.36%"
Date :
import datetime as dt
f"{dt.datetime.now():%Y-%m-%d}"
>>>"2019-03-27"
f"{dt.datetime.now():%d_%m_%Y}"
>>>"27_03_2019"
today = dt.datetime.today().strftime("%d_%m_%Y")
today
"27_03_2019"


Split without parameters :
"this is a  test".split()
>>>["this", "is", "a", "test"]
Concatenate :
"do"*2
>>>"dodo"
orig_string ="Hello"
orig_string+",World"
>>>"Hello,World"
full_sentence = orig_string+",World"
full_sentence
>>>"Hello,World"
Check string type , slice,count,strip :
strings = ["do","re","mi"]
", ".join(strings)
>>>"do, re, mi"
"z" not in "abc"
>>> True
ord("a"), ord("#")
>>> (97, 35)
chr(97)
>>>"a"
s = "foodbar"
s[2:5]
>>>"odb"
s[:4] + s[4:]
>>>"foodbar"
s[:4] + s[4:] == s
>>>True
t=s[:]
id(s)
>>>1547542895336
id(t)
>>>1547542895336
s is t
>>>True
s[0:6:2]
>>>"fob"
s[5:0:-2]
>>>"ado"
s = "tomorrow is monday"
reverse_s = s[::-1]
reverse_s
>>>"yadnom si worromot"
s.capitalize()
>>>"Tomorrow is monday"
s.upper()
>>>"TOMORROW IS MONDAY"
s.title()
>>>"Tomorrow Is Monday"
s.count("o")
>>> 4
"foobar".startswith("foo")
>>>True
"foobar".endswith("ar")
>>>True
"foobar".endswith("oob",0,4)
>>>True
"foobar".endswith("oob",2,4)
>>>False
"My name is yo, I work at SG".find("yo")
>>>11
# If can"t find the string, return -1
"My name is ya, I work at Gener".find("gent")
>>>-1
# Check a string if consists of alphanumeric characters
"abc123".isalnum()
>>>True
"abc%123".isalnum()
>>>False
"abcABC".isalpha()
>>>True
"abcABC1".isalpha()
>>>False
"123".isdigit()
>>>True
"123abc".isdigit()
>>>False
"abc".islower()
>>>True
"This Is A Title".istitle()
>>>True
"This is a title".istitle()
>>>False
"ABC".isupper()
>>>True
"ABC1%".isupper()
>>>True
"foo".center(10)
>>>"   foo    "
"   foo bar baz    ".strip()
>>>"foo bar baz"
"   foo bar baz    ".lstrip()
>>>"foo bar baz    "
"   foo bar baz    ".rstrip()
>>>"   foo bar baz"
"foo abc foo def fo  ljk ".replace("foo","yao")
>>>"yao abc yao def fo  ljk "
"www.realpython.com".strip("w.moc")
>>>"realpython"
"www.realpython.com".strip("w.com")
>>>"realpython"
"www.realpython.com".strip("w.ncom")
>>>"realpyth"
Convert to lists :
", ".join(["foo","bar","baz","qux"])
>>>"foo, bar, baz, qux"
list("corge")
>>>["c", "o", "r", "g", "e"]
":".join("corge")
>>>"c:o:r:g:e"
"www.foo".partition(".")
>>>("www", ".", "foo")
"foo@@bar@@baz".partition("@@")
>>>("foo", "@@", "bar@@baz")
"foo@@bar@@baz".rpartition("@@")
>>>("foo@@bar", "@@", "baz")
"foo.bar".partition("@@")
>>>("foo.bar", "", "")
# By default , rsplit split a string with white space
"foo bar adf yao".rsplit()
>>>["foo", "bar", "adf", "yao"]
"foo.bar.adf.ert".split(".")
>>>["foo", "bar", "adf", "ert"]
"foo
bar
adfa
lko".splitlines()
>>>["foo", "bar", "adfa", "lko"]
总结

除了我以上总结的这些,还有太多非常实用的方法,大家可以根据自己的需求去搜索啦!

我把这一期的ipynb文件和py文件放到了Github上,大家如果想要下载可以点击下面的链接:

Github仓库地址: https://github.com/yaozeliang/pandas_share

希望大家能够继续支持我,完结,撒花

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/43485.html

相关文章

  • Pandas之旅(一): 让我们把基础知识一次撸完,申精干货

    为什么你需要pandas 大家好,今天想和大家分享一下有关pandas的学习新的,我因工作需要,从去年12月开始接触这个非常好用的包,到现在为止也是算是熟悉了一些,因此发现了它的强大之处,特意想要和朋友们分享,特别是如果你每天和excel打交道,总是需要编写一些vba函数或者对行列进行groupby啊,merge,join啊之类的,相信我,pandas会让你解脱的。 好啦,闲话少说,这篇文章的基础...

    tuomao 评论0 收藏0
  • Pandas之旅(四) : 可能是社区内最实用Pandas技巧

    摘要:不为人知的七大实用技巧大家好,我今天勤快地回来了,这一期主要是和大家分享一些的实用技巧,会在日常生活中大大提升效率,希望可以帮助到大家还是老样子,先给大家奉上这一期的章节目录自定义选项,设置实用中模块构建测试数据巧用访问器合并其他列拼接使用 Pandas不为人知的七大实用技巧 大家好,我今天勤快地回来了,这一期主要是和大家分享一些pandas的实用技巧,会在日常生活中大大提升效率,希望...

    iflove 评论0 收藏0
  • Pandas之旅(三)最实用的Merge, Join,Concat方法详解

    摘要:基于上的我们还可以实现几个基于的,还是老样子,先让我们创建两个好了,现在我们想要实现两个的,但是条件是通过的和的这样我们也可以得到结果。 Merge, Join, Concat 大家好,我有回来啦,这周更新的有点慢,主要是因为我更新了个人简历哈哈,如果感兴趣的朋友可以去看看哈: 我的主页 个人认为还是很漂亮的~,不得不说,很多时候老外的设计能力还是很强。 好了,有点扯远了,这一期我想和...

    CloudwiseAPM 评论0 收藏0
  • Pandas之旅(二): 有关数据清理的点点滴滴

    摘要:数据清洗大家好,这一期我将为大家带来我的学习心得第二期数据清理。这一期我会和大家分享一些比较好用常见的清洗方法。首先还是让我们来简单看一下本文将会用到的数据源这是一个超小型的房地产行业的数据集,大家会在文章最后找到下载地址。 数据清洗 大家好,这一期我将为大家带来我的pandas学习心得第二期:数据清理。这一步非常重要,一般在获取数据源之后,我们紧接着就要开始这一步,以便为了之后的各种...

    wenyiweb 评论0 收藏0
  • ApacheCN 学习资源汇总 2019.3

    摘要:主页暂时下线社区暂时下线知识库自媒体平台微博知乎简书博客园合作侵权,请联系请抄送一份到特色项目中文文档和教程与机器学习实用指南人工智能机器学习数据科学比赛系列项目实战教程文档代码视频数据科学比赛收集平台,,剑指,经典算法实现系列课本课本描述 【主页】 apachecn.org 【Github】@ApacheCN 暂时下线: 社区 暂时下线: cwiki 知识库 自媒体平台 ...

    array_huang 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<