Retrieve dataframe row based on list from a cell valueHow do I sort a list of dictionaries by a value of the dictionary?How to randomly select an item from a list?Add one row to pandas DataFrameUse a list of values to select rows from a pandas dataframeDelete column from pandas DataFrame by column nameHow to drop rows of Pandas DataFrame whose value in certain columns is NaNHow to iterate over rows in a DataFrame in Pandas?Select rows from a DataFrame based on values in a column in pandasDeleting DataFrame row in Pandas based on column valueGet list from pandas DataFrame column headers

Is it a bad idea to replace pull-up resistors with hard pull-ups?

What are the components of a legend (in the sense of a tale, not a figure legend)?

How are Core iX names like Core i5, i7 related to Haswell, Ivy Bridge?

What stroke width Instagram is using for its icons and how to get same results?

How to slow yourself down (for playing nice with others)

Two researchers want to work on the same extension to my paper. Who to help?

Why does my circuit work on a breadboard, but not on a perfboard? I am new to soldering

Ex-manager wants to stay in touch, I don't want to

Does Lawful Interception of 4G / the proposed 5G provide a back door for hackers as well?

"Right on the tip of my tongue" meaning?

How to minimise the cost of guessing a number in a high/low guess game?

Is the schwa sound consistent?

Size of a folder with du

How to Access data returned from Apex class in JS controller using Lightning web component

How to compact two the parabol commands in the following example?

On studying Computer Science vs. Software Engineering to become a proficient coder

Meaning of「〜てみたいと思います」

Understanding integration over Orthogonal Group

Why was castling bad for white in this game, and engine strongly prefered trading queens?

What does a comma mean inside an 'if' statement?

Why doesn't Rocket Lab use a solid stage?

What is Plautus’s pun about frustum and frustrum?

Exclude loop* snap devices from lsblk output?

Why can't RGB or bicolour LEDs produce a decent yellow?



Retrieve dataframe row based on list from a cell value


How do I sort a list of dictionaries by a value of the dictionary?How to randomly select an item from a list?Add one row to pandas DataFrameUse a list of values to select rows from a pandas dataframeDelete column from pandas DataFrame by column nameHow to drop rows of Pandas DataFrame whose value in certain columns is NaNHow to iterate over rows in a DataFrame in Pandas?Select rows from a DataFrame based on values in a column in pandasDeleting DataFrame row in Pandas based on column valueGet list from pandas DataFrame column headers






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








0















I am trying to retrieve a row from a pandas dataframe where the cell value is a list. I have tried isin, but it looks like it is performing OR operation, not AND operation.



>>> import pandas as pd
>>> df = pd.DataFrame([['100', 'RB','stacked'], [['101','102'], 'CC','tagged'], ['102', 'S+C','tagged']],
columns=['vlan_id', 'mode' , 'tag_mode'],index=['dinesh','vj','mani'])

>>> df
vlan_id mode tag_mode
dinesh 100 RB stacked
vj [101, 102] CC tagged
mani 102 S+C tagged

>>> df.loc[df['vlan_id'] == '102']; # Fetching string value match
vlan_id mode tag_mode
mani 102 S+C tagged

>>> df.loc[df['vlan_id'].isin(['100','102'])]; # Fetching if contains either 100 or 102

vlan_id mode tag_mode
dinesh 100 RB stacked
mani 102 S+C tagged
>>> df.loc[df['vlan_id'] == ['101','102']]; # Fails ?
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:Python27libsite-packagespandascoreops.py", line 1283, in wrapper
res = na_op(values, other)
File "C:Python27libsite-packagespandascoreops.py", line 1143, in na_op
result = _comp_method_OBJECT_ARRAY(op, x, y)
File "C:Python27libsite-packagespandascoreops.py", line 1120, in _comp_method_OBJECT_ARRAY
result = libops.vec_compare(x, y, op)
File "pandas_libsops.pyx", line 128, in pandas._libs.ops.vec_compare
ValueError: Arrays were different lengths: 3 vs 2


I can get the values to a list and compare it. Instead, Is there any way available where we can check it against a list value using .loc method itself?










share|improve this question






























    0















    I am trying to retrieve a row from a pandas dataframe where the cell value is a list. I have tried isin, but it looks like it is performing OR operation, not AND operation.



    >>> import pandas as pd
    >>> df = pd.DataFrame([['100', 'RB','stacked'], [['101','102'], 'CC','tagged'], ['102', 'S+C','tagged']],
    columns=['vlan_id', 'mode' , 'tag_mode'],index=['dinesh','vj','mani'])

    >>> df
    vlan_id mode tag_mode
    dinesh 100 RB stacked
    vj [101, 102] CC tagged
    mani 102 S+C tagged

    >>> df.loc[df['vlan_id'] == '102']; # Fetching string value match
    vlan_id mode tag_mode
    mani 102 S+C tagged

    >>> df.loc[df['vlan_id'].isin(['100','102'])]; # Fetching if contains either 100 or 102

    vlan_id mode tag_mode
    dinesh 100 RB stacked
    mani 102 S+C tagged
    >>> df.loc[df['vlan_id'] == ['101','102']]; # Fails ?
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    File "C:Python27libsite-packagespandascoreops.py", line 1283, in wrapper
    res = na_op(values, other)
    File "C:Python27libsite-packagespandascoreops.py", line 1143, in na_op
    result = _comp_method_OBJECT_ARRAY(op, x, y)
    File "C:Python27libsite-packagespandascoreops.py", line 1120, in _comp_method_OBJECT_ARRAY
    result = libops.vec_compare(x, y, op)
    File "pandas_libsops.pyx", line 128, in pandas._libs.ops.vec_compare
    ValueError: Arrays were different lengths: 3 vs 2


    I can get the values to a list and compare it. Instead, Is there any way available where we can check it against a list value using .loc method itself?










    share|improve this question


























      0












      0








      0








      I am trying to retrieve a row from a pandas dataframe where the cell value is a list. I have tried isin, but it looks like it is performing OR operation, not AND operation.



      >>> import pandas as pd
      >>> df = pd.DataFrame([['100', 'RB','stacked'], [['101','102'], 'CC','tagged'], ['102', 'S+C','tagged']],
      columns=['vlan_id', 'mode' , 'tag_mode'],index=['dinesh','vj','mani'])

      >>> df
      vlan_id mode tag_mode
      dinesh 100 RB stacked
      vj [101, 102] CC tagged
      mani 102 S+C tagged

      >>> df.loc[df['vlan_id'] == '102']; # Fetching string value match
      vlan_id mode tag_mode
      mani 102 S+C tagged

      >>> df.loc[df['vlan_id'].isin(['100','102'])]; # Fetching if contains either 100 or 102

      vlan_id mode tag_mode
      dinesh 100 RB stacked
      mani 102 S+C tagged
      >>> df.loc[df['vlan_id'] == ['101','102']]; # Fails ?
      Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "C:Python27libsite-packagespandascoreops.py", line 1283, in wrapper
      res = na_op(values, other)
      File "C:Python27libsite-packagespandascoreops.py", line 1143, in na_op
      result = _comp_method_OBJECT_ARRAY(op, x, y)
      File "C:Python27libsite-packagespandascoreops.py", line 1120, in _comp_method_OBJECT_ARRAY
      result = libops.vec_compare(x, y, op)
      File "pandas_libsops.pyx", line 128, in pandas._libs.ops.vec_compare
      ValueError: Arrays were different lengths: 3 vs 2


      I can get the values to a list and compare it. Instead, Is there any way available where we can check it against a list value using .loc method itself?










      share|improve this question
















      I am trying to retrieve a row from a pandas dataframe where the cell value is a list. I have tried isin, but it looks like it is performing OR operation, not AND operation.



      >>> import pandas as pd
      >>> df = pd.DataFrame([['100', 'RB','stacked'], [['101','102'], 'CC','tagged'], ['102', 'S+C','tagged']],
      columns=['vlan_id', 'mode' , 'tag_mode'],index=['dinesh','vj','mani'])

      >>> df
      vlan_id mode tag_mode
      dinesh 100 RB stacked
      vj [101, 102] CC tagged
      mani 102 S+C tagged

      >>> df.loc[df['vlan_id'] == '102']; # Fetching string value match
      vlan_id mode tag_mode
      mani 102 S+C tagged

      >>> df.loc[df['vlan_id'].isin(['100','102'])]; # Fetching if contains either 100 or 102

      vlan_id mode tag_mode
      dinesh 100 RB stacked
      mani 102 S+C tagged
      >>> df.loc[df['vlan_id'] == ['101','102']]; # Fails ?
      Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "C:Python27libsite-packagespandascoreops.py", line 1283, in wrapper
      res = na_op(values, other)
      File "C:Python27libsite-packagespandascoreops.py", line 1143, in na_op
      result = _comp_method_OBJECT_ARRAY(op, x, y)
      File "C:Python27libsite-packagespandascoreops.py", line 1120, in _comp_method_OBJECT_ARRAY
      result = libops.vec_compare(x, y, op)
      File "pandas_libsops.pyx", line 128, in pandas._libs.ops.vec_compare
      ValueError: Arrays were different lengths: 3 vs 2


      I can get the values to a list and compare it. Instead, Is there any way available where we can check it against a list value using .loc method itself?







      python pandas numpy






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 23 at 12:33









      Mohit Motwani

      2,6061726




      2,6061726










      asked Mar 23 at 12:09









      DineshDinesh

      10.4k185897




      10.4k185897






















          3 Answers
          3






          active

          oldest

          votes


















          2














          To find a list you can iterate over the values of vlan_id and compare each value using np.array_equal:



          df.loc[[np.array_equal(x, ['101','102']) for x in df.vlan_id.values]]


          vlan_id mode tag_mode
          vj [101, 102] CC tagged


          Although, it's advised to avoid using lists as cell values in a dataframe.



          DataFrame.loc can use a list of labels or a Boolean array to access rows and columns. The list comprehension above contructs a Boolean array.






          share|improve this answer
































            0














            I am not sure if this is the best way to do this, or if there is a good way to do this, since as far as I know pandas doesn't really support storing lists in Series. Still:



            l = ['101', '102']

            df.loc[pd.concat([df['vlan_id'].str[i] == l[i] for i in range(len(l))], axis=1).all(axis=1)]


            Output:



             vlan_id mode tag_mode
            vj [101, 102] CC tagged





            share|improve this answer






























              0














              Another workaround would be to transform your vlan_id columns so that it can be queried as a string. You can do that by joining your vlan_id list values into comma-separated strings.



              df['proxy'] = df['vlan_id'].apply(lambda x: ','.join(x) if type(x) is list else ','.join([x]) )

              l = ','.join(['101', '102'])
              print(df.loc[df['proxy'] == l])





              share|improve this answer

























              • corrected, thanks!

                – dvitsios
                Mar 23 at 12:51











              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%2f55313584%2fretrieve-dataframe-row-based-on-list-from-a-cell-value%23new-answer', 'question_page');

              );

              Post as a guest















              Required, but never shown

























              3 Answers
              3






              active

              oldest

              votes








              3 Answers
              3






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              2














              To find a list you can iterate over the values of vlan_id and compare each value using np.array_equal:



              df.loc[[np.array_equal(x, ['101','102']) for x in df.vlan_id.values]]


              vlan_id mode tag_mode
              vj [101, 102] CC tagged


              Although, it's advised to avoid using lists as cell values in a dataframe.



              DataFrame.loc can use a list of labels or a Boolean array to access rows and columns. The list comprehension above contructs a Boolean array.






              share|improve this answer





























                2














                To find a list you can iterate over the values of vlan_id and compare each value using np.array_equal:



                df.loc[[np.array_equal(x, ['101','102']) for x in df.vlan_id.values]]


                vlan_id mode tag_mode
                vj [101, 102] CC tagged


                Although, it's advised to avoid using lists as cell values in a dataframe.



                DataFrame.loc can use a list of labels or a Boolean array to access rows and columns. The list comprehension above contructs a Boolean array.






                share|improve this answer



























                  2












                  2








                  2







                  To find a list you can iterate over the values of vlan_id and compare each value using np.array_equal:



                  df.loc[[np.array_equal(x, ['101','102']) for x in df.vlan_id.values]]


                  vlan_id mode tag_mode
                  vj [101, 102] CC tagged


                  Although, it's advised to avoid using lists as cell values in a dataframe.



                  DataFrame.loc can use a list of labels or a Boolean array to access rows and columns. The list comprehension above contructs a Boolean array.






                  share|improve this answer















                  To find a list you can iterate over the values of vlan_id and compare each value using np.array_equal:



                  df.loc[[np.array_equal(x, ['101','102']) for x in df.vlan_id.values]]


                  vlan_id mode tag_mode
                  vj [101, 102] CC tagged


                  Although, it's advised to avoid using lists as cell values in a dataframe.



                  DataFrame.loc can use a list of labels or a Boolean array to access rows and columns. The list comprehension above contructs a Boolean array.







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Mar 23 at 12:32

























                  answered Mar 23 at 12:20









                  Mohit MotwaniMohit Motwani

                  2,6061726




                  2,6061726























                      0














                      I am not sure if this is the best way to do this, or if there is a good way to do this, since as far as I know pandas doesn't really support storing lists in Series. Still:



                      l = ['101', '102']

                      df.loc[pd.concat([df['vlan_id'].str[i] == l[i] for i in range(len(l))], axis=1).all(axis=1)]


                      Output:



                       vlan_id mode tag_mode
                      vj [101, 102] CC tagged





                      share|improve this answer



























                        0














                        I am not sure if this is the best way to do this, or if there is a good way to do this, since as far as I know pandas doesn't really support storing lists in Series. Still:



                        l = ['101', '102']

                        df.loc[pd.concat([df['vlan_id'].str[i] == l[i] for i in range(len(l))], axis=1).all(axis=1)]


                        Output:



                         vlan_id mode tag_mode
                        vj [101, 102] CC tagged





                        share|improve this answer

























                          0












                          0








                          0







                          I am not sure if this is the best way to do this, or if there is a good way to do this, since as far as I know pandas doesn't really support storing lists in Series. Still:



                          l = ['101', '102']

                          df.loc[pd.concat([df['vlan_id'].str[i] == l[i] for i in range(len(l))], axis=1).all(axis=1)]


                          Output:



                           vlan_id mode tag_mode
                          vj [101, 102] CC tagged





                          share|improve this answer













                          I am not sure if this is the best way to do this, or if there is a good way to do this, since as far as I know pandas doesn't really support storing lists in Series. Still:



                          l = ['101', '102']

                          df.loc[pd.concat([df['vlan_id'].str[i] == l[i] for i in range(len(l))], axis=1).all(axis=1)]


                          Output:



                           vlan_id mode tag_mode
                          vj [101, 102] CC tagged






                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Mar 23 at 12:19









                          gmdsgmds

                          9,8941037




                          9,8941037





















                              0














                              Another workaround would be to transform your vlan_id columns so that it can be queried as a string. You can do that by joining your vlan_id list values into comma-separated strings.



                              df['proxy'] = df['vlan_id'].apply(lambda x: ','.join(x) if type(x) is list else ','.join([x]) )

                              l = ','.join(['101', '102'])
                              print(df.loc[df['proxy'] == l])





                              share|improve this answer

























                              • corrected, thanks!

                                – dvitsios
                                Mar 23 at 12:51















                              0














                              Another workaround would be to transform your vlan_id columns so that it can be queried as a string. You can do that by joining your vlan_id list values into comma-separated strings.



                              df['proxy'] = df['vlan_id'].apply(lambda x: ','.join(x) if type(x) is list else ','.join([x]) )

                              l = ','.join(['101', '102'])
                              print(df.loc[df['proxy'] == l])





                              share|improve this answer

























                              • corrected, thanks!

                                – dvitsios
                                Mar 23 at 12:51













                              0












                              0








                              0







                              Another workaround would be to transform your vlan_id columns so that it can be queried as a string. You can do that by joining your vlan_id list values into comma-separated strings.



                              df['proxy'] = df['vlan_id'].apply(lambda x: ','.join(x) if type(x) is list else ','.join([x]) )

                              l = ','.join(['101', '102'])
                              print(df.loc[df['proxy'] == l])





                              share|improve this answer















                              Another workaround would be to transform your vlan_id columns so that it can be queried as a string. You can do that by joining your vlan_id list values into comma-separated strings.



                              df['proxy'] = df['vlan_id'].apply(lambda x: ','.join(x) if type(x) is list else ','.join([x]) )

                              l = ','.join(['101', '102'])
                              print(df.loc[df['proxy'] == l])






                              share|improve this answer














                              share|improve this answer



                              share|improve this answer








                              edited Mar 23 at 12:51

























                              answered Mar 23 at 12:27









                              dvitsiosdvitsios

                              42027




                              42027












                              • corrected, thanks!

                                – dvitsios
                                Mar 23 at 12:51

















                              • corrected, thanks!

                                – dvitsios
                                Mar 23 at 12:51
















                              corrected, thanks!

                              – dvitsios
                              Mar 23 at 12:51





                              corrected, thanks!

                              – dvitsios
                              Mar 23 at 12:51

















                              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%2f55313584%2fretrieve-dataframe-row-based-on-list-from-a-cell-value%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

                              Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                              SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

                              은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현