如何删除 Pandas 中不以“x”开头的行或保留以“x”开头的行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35186291/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I delete rows not starting with 'x' in Pandas or keep rows starting with 'x'
提问by Mxracer888
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.
我整个上午都在做这件事,慢慢地把事情拼凑起来。但是对于我的生活,我无法弄清楚如何在 Pandas 中使用 .str.startswith() 函数。
My XLSX spreadsheet is as follows
我的 XLSX 电子表格如下
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...
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.'
所以我将它作为数据框导入,清理标题以便没有空格等,然后我想删除任何不以“1”开头的行。(或保留以“1.”开头的行)并删除所有其他行。因此,在这个简短的示例中,删除整个“Jane Doe”条目,因为她的电话号码以“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')
But all that does is convert all phone values to 'NaN', it maintains all of the rows and everything as shown below:
但所做的只是将所有电话值转换为“NaN”,它维护所有行和所有内容,如下所示:
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
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?
我已经搜索了太多地方甚至无法列出,我尝试了不同版本的 df.drop 并且似乎无法弄清楚任何事情。我从这里去哪里?
回答by Ami Tavory
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
带有 column的 DataFrame 'c'
,并且您想删除以 开头的项目1
,那么最安全的方法是使用以下内容:
df = df[~df['c'].astype(str).str.startswith('1')]