python - Python Pandas: Filter rows based on position letter in string
问题描述
I'm pretty new to python and I'm still learning Pandas. I've been playing around and trying to learn things with Pandas that I wouldn't be able to do with excel ordinaril using it's filter function.
One thing that I have been trying to do is to filter based on the second letter in the column I choose to filter through.
For example, I have the following table:
Name HP Type
Pikachu 10 Electric
Charizard 200 Fire
Squirtle 300 Water
I want to create a filter that looks through the name column and if the second letter is 'h' then it gives me the data for charizard row.
In other words, it filters data by row based on the second letter specified in the column selected, in this case the column is "Name" and the letter was 'h'
I've tried to make this code by using a for loop and and index function but after trying for quite some time, I was unable to properly get it done and I wanted some feedback as to how I would go about appraoching this.
My code looks like the following:
import pandas as pd
df = pd.read_excel (r'C:\Users\Name\Desktop\pokemon.xlsx')
for column in (df['Name']):
if column.index[1] == 'h':
print (df [['Name', 'HP', 'Type']])
I'm new to this, so any tips on how to fix my code would be appreciated. Thanks.
解决方案
IIUC,然后str.contains
与regex
比赛一起使用。
df[df.Name.str.contains(r'^\wh\w*')]
印刷:
Name HP Type
1 Charizard 200 Fire
推荐阅读
- javascript - 随机工作的锚上的 preventdefault() 函数
- node.js - 尽管使用 app.use(bodyParser.urlencoded({extended: true})); 节点 js 程序中没有正文参数。
- java - java.lang.IllegalArgumentException:不支持的类文件主要版本 55 - 从 Jenkins 服务器运行 Gradle 构建时
- android - 如何在通知点击时转到特定活动?
- flutter - Rxdart CombineLatest 与可选字段相结合
- python - 如何在python 3中计算拉普拉斯函数
- python - 缺少值时如何旋转和重命名连接的级别列?
- postgresql - 在 Postgresql 中,相同的词对相同的查询给出真假
- asp.net-mvc - 限制(阻止)用户在 ASP.Net MVC 中使用相同的凭据多次登录
- django - 如何预先填写数据库中已经存在的表单字段中的值并交付部分表单或获取剩余的输入