Change column values in pandas based on condition









up vote
1
down vote

favorite












df:



 A
0 219
1 590
2 272
3 945
4 175
5 930
6 662
7 472
8 251
9 130


I am trying to create a new column quantile based on which quantile the value falls in, for example:



if value > 1st quantile : value = 1
if value > 2nd quantile : value = 2
if value > 3rd quantile : value = 3
if value > 4th quantile : value = 4


Code:



f_q = df['A'] .quantile (0.25)
s_q = df['A'] .quantile (0.5)
t_q = df['A'] .quantile (0.75)
fo_q = df['A'] .quantile (1)


index = 0
for i in range(len(test_df)):

value = df.at[index,"A"]
if value > 0 and value <= f_q:
df.at[index,"A"] = 1

elif value > f_q and value <= s_q:
df.at[index,"A"] = 2

elif value > s_q and value <= t_q:
df.at[index,"A"] = 3

elif value > t_q and value <= fo_q:
df.at[index,"A"] = 4


index += 1


The code works fine. But I would like to know if there is a more efficient pandas way of doing this. Any suggestions are helpful.










share|improve this question



























    up vote
    1
    down vote

    favorite












    df:



     A
    0 219
    1 590
    2 272
    3 945
    4 175
    5 930
    6 662
    7 472
    8 251
    9 130


    I am trying to create a new column quantile based on which quantile the value falls in, for example:



    if value > 1st quantile : value = 1
    if value > 2nd quantile : value = 2
    if value > 3rd quantile : value = 3
    if value > 4th quantile : value = 4


    Code:



    f_q = df['A'] .quantile (0.25)
    s_q = df['A'] .quantile (0.5)
    t_q = df['A'] .quantile (0.75)
    fo_q = df['A'] .quantile (1)


    index = 0
    for i in range(len(test_df)):

    value = df.at[index,"A"]
    if value > 0 and value <= f_q:
    df.at[index,"A"] = 1

    elif value > f_q and value <= s_q:
    df.at[index,"A"] = 2

    elif value > s_q and value <= t_q:
    df.at[index,"A"] = 3

    elif value > t_q and value <= fo_q:
    df.at[index,"A"] = 4


    index += 1


    The code works fine. But I would like to know if there is a more efficient pandas way of doing this. Any suggestions are helpful.










    share|improve this question

























      up vote
      1
      down vote

      favorite









      up vote
      1
      down vote

      favorite











      df:



       A
      0 219
      1 590
      2 272
      3 945
      4 175
      5 930
      6 662
      7 472
      8 251
      9 130


      I am trying to create a new column quantile based on which quantile the value falls in, for example:



      if value > 1st quantile : value = 1
      if value > 2nd quantile : value = 2
      if value > 3rd quantile : value = 3
      if value > 4th quantile : value = 4


      Code:



      f_q = df['A'] .quantile (0.25)
      s_q = df['A'] .quantile (0.5)
      t_q = df['A'] .quantile (0.75)
      fo_q = df['A'] .quantile (1)


      index = 0
      for i in range(len(test_df)):

      value = df.at[index,"A"]
      if value > 0 and value <= f_q:
      df.at[index,"A"] = 1

      elif value > f_q and value <= s_q:
      df.at[index,"A"] = 2

      elif value > s_q and value <= t_q:
      df.at[index,"A"] = 3

      elif value > t_q and value <= fo_q:
      df.at[index,"A"] = 4


      index += 1


      The code works fine. But I would like to know if there is a more efficient pandas way of doing this. Any suggestions are helpful.










      share|improve this question















      df:



       A
      0 219
      1 590
      2 272
      3 945
      4 175
      5 930
      6 662
      7 472
      8 251
      9 130


      I am trying to create a new column quantile based on which quantile the value falls in, for example:



      if value > 1st quantile : value = 1
      if value > 2nd quantile : value = 2
      if value > 3rd quantile : value = 3
      if value > 4th quantile : value = 4


      Code:



      f_q = df['A'] .quantile (0.25)
      s_q = df['A'] .quantile (0.5)
      t_q = df['A'] .quantile (0.75)
      fo_q = df['A'] .quantile (1)


      index = 0
      for i in range(len(test_df)):

      value = df.at[index,"A"]
      if value > 0 and value <= f_q:
      df.at[index,"A"] = 1

      elif value > f_q and value <= s_q:
      df.at[index,"A"] = 2

      elif value > s_q and value <= t_q:
      df.at[index,"A"] = 3

      elif value > t_q and value <= fo_q:
      df.at[index,"A"] = 4


      index += 1


      The code works fine. But I would like to know if there is a more efficient pandas way of doing this. Any suggestions are helpful.







      python pandas






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 10 at 3:38









      coldspeed

      111k17101170




      111k17101170










      asked Nov 10 at 3:13









      vikky

      6231128




      6231128






















          1 Answer
          1






          active

          oldest

          votes

















          up vote
          2
          down vote



          accepted










          Yes, using pd.qcut:



          >>> pd.qcut(df.A, 4).cat.codes + 1
          0 1
          1 3
          2 2
          3 4
          4 1
          5 4
          6 4
          7 3
          8 2
          9 1
          dtype: int8


          (Gives me exactly the same result your code does.)



          You could also call np.unique on the qcut result:



          >>> np.unique(pd.qcut(df.A, 4), return_inverse=True)[1] + 1
          array([1, 3, 2, 4, 1, 4, 4, 3, 2, 1])


          Or, using pd.factorize (note the slight difference in the output):



          >>> pd.factorize(pd.qcut(df.A, 4))[0] + 1
          array([1, 2, 3, 4, 1, 4, 4, 2, 3, 1])





          share|improve this answer


















          • 1




            wow!! thanks for the suggestion. This is great.
            – vikky
            Nov 10 at 3:20










          • @vikky Added more options, if needed.
            – coldspeed
            Nov 10 at 3:25










          • cool Thanks. i will compare the performances of the options and will post that for future readers.
            – vikky
            Nov 10 at 3:30










          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',
          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%2f53235718%2fchange-column-values-in-pandas-based-on-condition%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








          up vote
          2
          down vote



          accepted










          Yes, using pd.qcut:



          >>> pd.qcut(df.A, 4).cat.codes + 1
          0 1
          1 3
          2 2
          3 4
          4 1
          5 4
          6 4
          7 3
          8 2
          9 1
          dtype: int8


          (Gives me exactly the same result your code does.)



          You could also call np.unique on the qcut result:



          >>> np.unique(pd.qcut(df.A, 4), return_inverse=True)[1] + 1
          array([1, 3, 2, 4, 1, 4, 4, 3, 2, 1])


          Or, using pd.factorize (note the slight difference in the output):



          >>> pd.factorize(pd.qcut(df.A, 4))[0] + 1
          array([1, 2, 3, 4, 1, 4, 4, 2, 3, 1])





          share|improve this answer


















          • 1




            wow!! thanks for the suggestion. This is great.
            – vikky
            Nov 10 at 3:20










          • @vikky Added more options, if needed.
            – coldspeed
            Nov 10 at 3:25










          • cool Thanks. i will compare the performances of the options and will post that for future readers.
            – vikky
            Nov 10 at 3:30














          up vote
          2
          down vote



          accepted










          Yes, using pd.qcut:



          >>> pd.qcut(df.A, 4).cat.codes + 1
          0 1
          1 3
          2 2
          3 4
          4 1
          5 4
          6 4
          7 3
          8 2
          9 1
          dtype: int8


          (Gives me exactly the same result your code does.)



          You could also call np.unique on the qcut result:



          >>> np.unique(pd.qcut(df.A, 4), return_inverse=True)[1] + 1
          array([1, 3, 2, 4, 1, 4, 4, 3, 2, 1])


          Or, using pd.factorize (note the slight difference in the output):



          >>> pd.factorize(pd.qcut(df.A, 4))[0] + 1
          array([1, 2, 3, 4, 1, 4, 4, 2, 3, 1])





          share|improve this answer


















          • 1




            wow!! thanks for the suggestion. This is great.
            – vikky
            Nov 10 at 3:20










          • @vikky Added more options, if needed.
            – coldspeed
            Nov 10 at 3:25










          • cool Thanks. i will compare the performances of the options and will post that for future readers.
            – vikky
            Nov 10 at 3:30












          up vote
          2
          down vote



          accepted







          up vote
          2
          down vote



          accepted






          Yes, using pd.qcut:



          >>> pd.qcut(df.A, 4).cat.codes + 1
          0 1
          1 3
          2 2
          3 4
          4 1
          5 4
          6 4
          7 3
          8 2
          9 1
          dtype: int8


          (Gives me exactly the same result your code does.)



          You could also call np.unique on the qcut result:



          >>> np.unique(pd.qcut(df.A, 4), return_inverse=True)[1] + 1
          array([1, 3, 2, 4, 1, 4, 4, 3, 2, 1])


          Or, using pd.factorize (note the slight difference in the output):



          >>> pd.factorize(pd.qcut(df.A, 4))[0] + 1
          array([1, 2, 3, 4, 1, 4, 4, 2, 3, 1])





          share|improve this answer














          Yes, using pd.qcut:



          >>> pd.qcut(df.A, 4).cat.codes + 1
          0 1
          1 3
          2 2
          3 4
          4 1
          5 4
          6 4
          7 3
          8 2
          9 1
          dtype: int8


          (Gives me exactly the same result your code does.)



          You could also call np.unique on the qcut result:



          >>> np.unique(pd.qcut(df.A, 4), return_inverse=True)[1] + 1
          array([1, 3, 2, 4, 1, 4, 4, 3, 2, 1])


          Or, using pd.factorize (note the slight difference in the output):



          >>> pd.factorize(pd.qcut(df.A, 4))[0] + 1
          array([1, 2, 3, 4, 1, 4, 4, 2, 3, 1])






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 10 at 3:24

























          answered Nov 10 at 3:19









          coldspeed

          111k17101170




          111k17101170







          • 1




            wow!! thanks for the suggestion. This is great.
            – vikky
            Nov 10 at 3:20










          • @vikky Added more options, if needed.
            – coldspeed
            Nov 10 at 3:25










          • cool Thanks. i will compare the performances of the options and will post that for future readers.
            – vikky
            Nov 10 at 3:30












          • 1




            wow!! thanks for the suggestion. This is great.
            – vikky
            Nov 10 at 3:20










          • @vikky Added more options, if needed.
            – coldspeed
            Nov 10 at 3:25










          • cool Thanks. i will compare the performances of the options and will post that for future readers.
            – vikky
            Nov 10 at 3:30







          1




          1




          wow!! thanks for the suggestion. This is great.
          – vikky
          Nov 10 at 3:20




          wow!! thanks for the suggestion. This is great.
          – vikky
          Nov 10 at 3:20












          @vikky Added more options, if needed.
          – coldspeed
          Nov 10 at 3:25




          @vikky Added more options, if needed.
          – coldspeed
          Nov 10 at 3:25












          cool Thanks. i will compare the performances of the options and will post that for future readers.
          – vikky
          Nov 10 at 3:30




          cool Thanks. i will compare the performances of the options and will post that for future readers.
          – vikky
          Nov 10 at 3:30

















          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.





          Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


          Please pay close attention to the following guidance:


          • 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%2f53235718%2fchange-column-values-in-pandas-based-on-condition%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

          Use pre created SQLite database for Android project in kotlin

          Darth Vader #20

          Ondo