Dropping row in pandas by index - have to add to index?Finding the index of an item given a list containing it in PythonDoes Python have a ternary conditional operator?Accessing the index in 'for' loops?Add new keys to a dictionary?Does Python have a string 'contains' substring method?Add one row to pandas DataFrameRenaming columns in pandas“Large data” work flows using pandasHow to iterate over rows in a DataFrame in Pandas?Select rows from a DataFrame based on values in a column in pandas

Increase performance creating Mandelbrot set in python

Was Spock the First Vulcan in Starfleet?

Gears on left are inverse to gears on right?

Lay out the Carpet

Risk of infection at the gym?

Is there a problem with hiding "forgot password" until it's needed?

Trouble understanding the speech of overseas colleagues

For a non-Jew, is there a punishment for not observing the 7 Noahide Laws?

Is this version of a gravity generator feasible?

Purchasing a ticket for someone else in another country?

How can we prove that any integral in the set of non-elementary integrals cannot be expressed in the form of elementary functions?

How easy is it to start Magic from scratch?

How do we know the LHC results are robust?

Is a stroke of luck acceptable after a series of unfavorable events?

Failed to fetch jessie backports repository

Why Were Madagascar and New Zealand Discovered So Late?

Closest Prime Number

Hostile work environment after whistle-blowing on coworker and our boss. What do I do?

Proof of work - lottery approach

What is the intuitive meaning of having a linear relationship between the logs of two variables?

What can we do to stop prior company from asking us questions?

Did Dumbledore lie to Harry about how long he had James Potter's invisibility cloak when he was examining it? If so, why?

Opposite of a diet

Is there a good way to store credentials outside of a password manager?



Dropping row in pandas by index - have to add to index?


Finding the index of an item given a list containing it in PythonDoes Python have a ternary conditional operator?Accessing the index in 'for' loops?Add new keys to a dictionary?Does Python have a string 'contains' substring method?Add one row to pandas DataFrameRenaming columns in pandas“Large data” work flows using pandasHow to iterate over rows in a DataFrame in Pandas?Select rows from a DataFrame based on values in a column in pandas













1















I have a pandas dataframe of 182 rows that comes from read_csv. The first column, sys_code, contains various alphanumeric codes. I want to drop ones that start with 'FB' (there are 14 of these). I loop through the dataframe, adding what I assume would be the index to a list, then try to drop by index using the list. But this doesn't work unless I add 18 to each index number.



Without adding 18, I get a list containing numbers from 84 - 97. When I try to drop the rows using this list for indexes, I get KeyError: '[84] not found in axis'. But when I add 18 to each number, it works fine, at least for this particular dataset. But why is this? Shouldn't i be the same as the index number?



fb = []
i = 0
df.reset_index(drop=True)
for x in df['sys_code']:
if x[:2] == 'FB':
fb.append(i+18) #works
fb.append(i) # doesn't work
i += 1
df.drop(fb, axis=0, inplace=True)









share|improve this question




























    1















    I have a pandas dataframe of 182 rows that comes from read_csv. The first column, sys_code, contains various alphanumeric codes. I want to drop ones that start with 'FB' (there are 14 of these). I loop through the dataframe, adding what I assume would be the index to a list, then try to drop by index using the list. But this doesn't work unless I add 18 to each index number.



    Without adding 18, I get a list containing numbers from 84 - 97. When I try to drop the rows using this list for indexes, I get KeyError: '[84] not found in axis'. But when I add 18 to each number, it works fine, at least for this particular dataset. But why is this? Shouldn't i be the same as the index number?



    fb = []
    i = 0
    df.reset_index(drop=True)
    for x in df['sys_code']:
    if x[:2] == 'FB':
    fb.append(i+18) #works
    fb.append(i) # doesn't work
    i += 1
    df.drop(fb, axis=0, inplace=True)









    share|improve this question


























      1












      1








      1








      I have a pandas dataframe of 182 rows that comes from read_csv. The first column, sys_code, contains various alphanumeric codes. I want to drop ones that start with 'FB' (there are 14 of these). I loop through the dataframe, adding what I assume would be the index to a list, then try to drop by index using the list. But this doesn't work unless I add 18 to each index number.



      Without adding 18, I get a list containing numbers from 84 - 97. When I try to drop the rows using this list for indexes, I get KeyError: '[84] not found in axis'. But when I add 18 to each number, it works fine, at least for this particular dataset. But why is this? Shouldn't i be the same as the index number?



      fb = []
      i = 0
      df.reset_index(drop=True)
      for x in df['sys_code']:
      if x[:2] == 'FB':
      fb.append(i+18) #works
      fb.append(i) # doesn't work
      i += 1
      df.drop(fb, axis=0, inplace=True)









      share|improve this question
















      I have a pandas dataframe of 182 rows that comes from read_csv. The first column, sys_code, contains various alphanumeric codes. I want to drop ones that start with 'FB' (there are 14 of these). I loop through the dataframe, adding what I assume would be the index to a list, then try to drop by index using the list. But this doesn't work unless I add 18 to each index number.



      Without adding 18, I get a list containing numbers from 84 - 97. When I try to drop the rows using this list for indexes, I get KeyError: '[84] not found in axis'. But when I add 18 to each number, it works fine, at least for this particular dataset. But why is this? Shouldn't i be the same as the index number?



      fb = []
      i = 0
      df.reset_index(drop=True)
      for x in df['sys_code']:
      if x[:2] == 'FB':
      fb.append(i+18) #works
      fb.append(i) # doesn't work
      i += 1
      df.drop(fb, axis=0, inplace=True)






      python python-3.x pandas






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 7 at 13:18









      Shanteshwar Inde

      7421918




      7421918










      asked Mar 7 at 12:49









      recurvatarecurvata

      225




      225






















          1 Answer
          1






          active

          oldest

          votes


















          2














          You could use Series.str.startswith. Here's an example:



          df = pd.DataFrame('col1':['some string', 'FBsomething', 'FB', 'etc'])
          print(df)

          col1
          0 some string
          1 FBsomething
          2 FB
          3 etc


          You could remove those strings that do not start with FB using:



          df[~df.col1.str.startswith('FB')]

          col1
          0 some string
          3 etc





          share|improve this answer


















          • 1





            Thanks, was not aware of that syntax with the ~ symbol. I had to modify the code a bit - df = df[~df.col1.str.startswith('FB')], but works great. Still don't know why original code gave error though.

            – recurvata
            Mar 7 at 13:28










          Your Answer






          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "1"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55044204%2fdropping-row-in-pandas-by-index-have-to-add-to-index%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          2














          You could use Series.str.startswith. Here's an example:



          df = pd.DataFrame('col1':['some string', 'FBsomething', 'FB', 'etc'])
          print(df)

          col1
          0 some string
          1 FBsomething
          2 FB
          3 etc


          You could remove those strings that do not start with FB using:



          df[~df.col1.str.startswith('FB')]

          col1
          0 some string
          3 etc





          share|improve this answer


















          • 1





            Thanks, was not aware of that syntax with the ~ symbol. I had to modify the code a bit - df = df[~df.col1.str.startswith('FB')], but works great. Still don't know why original code gave error though.

            – recurvata
            Mar 7 at 13:28















          2














          You could use Series.str.startswith. Here's an example:



          df = pd.DataFrame('col1':['some string', 'FBsomething', 'FB', 'etc'])
          print(df)

          col1
          0 some string
          1 FBsomething
          2 FB
          3 etc


          You could remove those strings that do not start with FB using:



          df[~df.col1.str.startswith('FB')]

          col1
          0 some string
          3 etc





          share|improve this answer


















          • 1





            Thanks, was not aware of that syntax with the ~ symbol. I had to modify the code a bit - df = df[~df.col1.str.startswith('FB')], but works great. Still don't know why original code gave error though.

            – recurvata
            Mar 7 at 13:28













          2












          2








          2







          You could use Series.str.startswith. Here's an example:



          df = pd.DataFrame('col1':['some string', 'FBsomething', 'FB', 'etc'])
          print(df)

          col1
          0 some string
          1 FBsomething
          2 FB
          3 etc


          You could remove those strings that do not start with FB using:



          df[~df.col1.str.startswith('FB')]

          col1
          0 some string
          3 etc





          share|improve this answer













          You could use Series.str.startswith. Here's an example:



          df = pd.DataFrame('col1':['some string', 'FBsomething', 'FB', 'etc'])
          print(df)

          col1
          0 some string
          1 FBsomething
          2 FB
          3 etc


          You could remove those strings that do not start with FB using:



          df[~df.col1.str.startswith('FB')]

          col1
          0 some string
          3 etc






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Mar 7 at 12:53









          yatuyatu

          15k41542




          15k41542







          • 1





            Thanks, was not aware of that syntax with the ~ symbol. I had to modify the code a bit - df = df[~df.col1.str.startswith('FB')], but works great. Still don't know why original code gave error though.

            – recurvata
            Mar 7 at 13:28












          • 1





            Thanks, was not aware of that syntax with the ~ symbol. I had to modify the code a bit - df = df[~df.col1.str.startswith('FB')], but works great. Still don't know why original code gave error though.

            – recurvata
            Mar 7 at 13:28







          1




          1





          Thanks, was not aware of that syntax with the ~ symbol. I had to modify the code a bit - df = df[~df.col1.str.startswith('FB')], but works great. Still don't know why original code gave error though.

          – recurvata
          Mar 7 at 13:28





          Thanks, was not aware of that syntax with the ~ symbol. I had to modify the code a bit - df = df[~df.col1.str.startswith('FB')], but works great. Still don't know why original code gave error though.

          – recurvata
          Mar 7 at 13:28



















          draft saved

          draft discarded
















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55044204%2fdropping-row-in-pandas-by-index-have-to-add-to-index%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          AWS Lex not identifying response if by a variable The 2019 Stack Overflow Developer Survey Results Are In Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern) The Ask Question Wizard is Live! Data science time! April 2019 and salary with experienceEnforcing custom enumeration in AWS LEX for slot valuesHow to give response based on user response in Amazon Lex?Intercepting AWS Lambda Response to a AWS Lex QueryLex chat bot error: Reached second execution of fulfillment lambda on the same utteranceamazon lex showing invalid responseLambda response send back to Lex slot?Response card in Amazon lexAmazon Lex - Lambda response return HTML to botHow can I solve 424 (Failed Dependency) (python) obtained from Amazon lex?

          Алба-Юлія

          Захаров Федір Захарович