本节使用的数据为 data/titanic.csv
,链接为 pandas案例和教程所使用的数据-机器学习文档类资源-CSDN文库
import pandas as pd
titanic = pd.read_csv("data/titanic.csv")
PassengerId Survived Pclass \
0 1 0 3
1 2 1 1
2 3 1 3
3 4 1 1
4 5 0 3
Name Sex Age SibSp \
0 Braund, Mr. Owen Harris male 22.0 1
1 Cumings, Mrs. John Bradley (Florence Briggs Th... female 38.0 1
2 Heikkinen, Miss. Laina female 26.0 0
3 Futrelle, Mrs. Jacques Heath (Lily May Peel) female 35.0 1
4 Allen, Mr. William Henry male 35.0 0
Parch Ticket Fare Cabin Embarked
0 0 A/5 21171 7.2500 NaN S
1 0 PC 17599 71.2833 C85 C
2 0 STON/O2. 3101282 7.9250 NaN S
3 0 113803 53.1000 C123 S
4 0 373450 8.0500 NaN S
titanic["Name"].str.lower()
0 braund, mr. owen harris
1 cumings, mrs. john bradley (florence briggs th...
2 heikkinen, miss. laina
3 futrelle, mrs. jacques heath (lily may peel)
4 allen, mr. william henry
...
886 montvila, rev. juozas
887 graham, miss. margaret edith
888 johnston, miss. catherine helen "carrie"
889 behr, mr. karl howell
890 dooley, mr. patrick
Name: Name, Length: 891, dtype: object
与时间序列里的
dt
类似,字符串有str
可以访问很多字符操作的方法。
# 以下语句可以将姓氏用逗号分离
# titanic["Surname"] = titanic["Name"].str.split(",")
titanic["Surname"] = titanic["Name"].str.split(",").str.get(0)
titanic["Surname"]
0 Braund
1 Cumings
2 Heikkinen
3 Futrelle
4 Allen
...
886 Montvila
887 Graham
888 Johnston
889 Behr
890 Dooley
Name: Surname, Length: 891, dtype: object
# 可以通过 contains 方法获得一个布尔值表示名字是否包含某个字符串
# titanic["Name"].str.contains("Countess")
titanic[titanic["Name"].str.contains("Countess")]
PassengerId Survived Pclass \
759 760 1 1
Name Sex Age SibSp \
759 Rothes, the Countess. of (Lucy Noel Martha Dye... female 33.0 0
Parch Ticket Fare Cabin Embarked Surname
759 0 110152 86.5 B77 S Rothes
# 获得每个乘客名字的长度
# titanic["Name"].str.len()
titanic["Name"].str.len().idxmax()
## output
307
idxmax
方法可以返回最大值的索引,如果要知道最长名字是什么?可以用以下语句
titanic.loc[titanic["Name"].str.len().idxmax(), "Name"]
'Penasco y Castellana, Mrs. Victor de Satode (Maria Josefa Perez de Soto y Vallejo)'
male
和 female
替换为 M
和 F
titanic["Sex_short"] = titanic["Sex"].replace({"male":"M", "female":"F"})
titanic["Sex_short"]
0 M
1 F
2 F
3 F
4 M
..
886 M
887 F
888 F
889 M
890 M
Name: Sex_short, Length: 891, dtype: object
也可以按照如下方法完成
titanic["Sex_short"] = titanic["Sex"].str.replace("female", "F") titanic["Sex_short"] = titanic["Sex_short"].str.replace("male", "M")
字符串的方法可以通过
str
进行访问,类似于时间序列的dt
字符串方法按元素工作,可用于条件索引。
replace
方法可以方便的将字符串用字典的方式进行替换。
How to manipulate textual data? — pandas 1.5.2 documentation (pydata.org)