如何删除 Pandas 中不以“x"开头的行或保留以“x"开头的行 [英] How do I delete rows not starting with 'x' in Pandas or keep rows starting with 'x'

查看:61
本文介绍了如何删除 Pandas 中不以“x"开头的行或保留以“x"开头的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我整个上午都在做这件事,慢慢地把事情拼凑起来.但是对于我的生活,我无法弄清楚如何在 Pandas 中使用 .str.startswith() 函数.

I have been at this all morning and have slowly pieced things together. But for the life of me I can not figure out how to use the .str.startswith() function in Pandas.

我的 XLSX 电子表格如下

My XLSX spreadsheet is as follows

1 Name, Registration Date, Phone number
2 John Doe, 2015-11-20T19:54:45Z, 1.1112223333
3 Jane Doe, 2015-11-20T20:44:26Z, 65.1112223333
etc...

所以我将它作为数据框导入,清理标题以便没有空格等,然后我想删除任何不以1"开头的行.(或保留以1."开头的行)并删除所有其他行.因此,在这个简短的示例中,删除整个Jane Doe"条目,因为她的电话号码以65"开头.

So I am importing it as a data frame, cleaning the header so that there are no spaces and such, then I want to delete any rows not starting with '1.' (or keep rows that start with '1.') and delete all others. So in this short example, delete the entire 'Jane Doe' entry since her phone number starts with '65.'

import pandas as pd
df = pd.read_excel('testingpanda.xlsx', sheetname = 'Export 1')
def colHeaderCleaner():
    cols = df.columns
    cols = cols.map(lambda x: x.replace(' ', '_') if isinstance(x, (str, unicode)) else x)
    df.columns = cols
    df.columns = [x.lower() for x in df.columns]

colHeaderCleaner()

#by default it sets the values in 'registrant_phone' as float64, so this is fixing that...
df['registrant_phone'] = df['registrant_phone'].astype('object')

我得到的最接近的,我的意思是我能够执行而没有烦人的回溯和其他错误的唯一一行是:

The closest I have gotten, and by that I mean the only line I have been able to execute without annoying tracebacks and other errors is:

df['registrant_phone'] = df['registrant_phone'].str.startswith('1')

但所做的只是将所有电话值转换为NaN",它维护所有行和所有内容,如下所示:

But all that does is convert all phone values to 'NaN', it maintains all of the rows and everything as shown below:

print df
[output] name, registration_date, phone_number
[output] John Doe, 2015-11-20T19:54:45Z, NaN
[output] Jane Doe, 2015-11-20T20:44:26Z, NaN

我搜索了太多地方甚至无法列出,我尝试了不同版本的 df.drop 并且似乎无法弄清楚任何事情.我从这里去哪里?

I have searched far too many places to even try to list, I have tried different versions of df.drop and just can't seem to figure anything out. Where do I go from here?

推荐答案

我对你的问题有点困惑.在任何情况下,如果您有一个带有 'c' 列的 DataFrame df,并且您想删除以 1 开头的项目,那么最安全的方法是使用类似的东西:

I am a bit confused by your question. In any case, if you have a DataFrame df with a column 'c', and you would like to remove the items starting with 1, then the safest way would be to use something like:

df = df[~df['c'].astype(str).str.startswith('1')]

这篇关于如何删除 Pandas 中不以“x"开头的行或保留以“x"开头的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆