How to get a value of a column based on the id's given from another table












1














I wanted to extract the value of a column given another column with id's of a different dataset.



DF-1:



ID  A       B
1 cat 22
2 dog 33
3 mamal 44
4 rat 55
5 rabbit 66
6 puppy 77


DF-2:



name   fav_animal
x 1,2,3
y 2,3
z 3,4


I wanted to see the fav animals of x in a new list say name_animal.



code:



#storing all the id's of x frist
list_id =
name_animal =
for i in list_ids:
name_animal.append(df1.loc[df1.id == i, 'A'].values.to_list()


Output:



list_id = [1,2,3]
name_animal = ['cat','dog','mamal']









share|improve this question



























    1














    I wanted to extract the value of a column given another column with id's of a different dataset.



    DF-1:



    ID  A       B
    1 cat 22
    2 dog 33
    3 mamal 44
    4 rat 55
    5 rabbit 66
    6 puppy 77


    DF-2:



    name   fav_animal
    x 1,2,3
    y 2,3
    z 3,4


    I wanted to see the fav animals of x in a new list say name_animal.



    code:



    #storing all the id's of x frist
    list_id =
    name_animal =
    for i in list_ids:
    name_animal.append(df1.loc[df1.id == i, 'A'].values.to_list()


    Output:



    list_id = [1,2,3]
    name_animal = ['cat','dog','mamal']









    share|improve this question

























      1












      1








      1







      I wanted to extract the value of a column given another column with id's of a different dataset.



      DF-1:



      ID  A       B
      1 cat 22
      2 dog 33
      3 mamal 44
      4 rat 55
      5 rabbit 66
      6 puppy 77


      DF-2:



      name   fav_animal
      x 1,2,3
      y 2,3
      z 3,4


      I wanted to see the fav animals of x in a new list say name_animal.



      code:



      #storing all the id's of x frist
      list_id =
      name_animal =
      for i in list_ids:
      name_animal.append(df1.loc[df1.id == i, 'A'].values.to_list()


      Output:



      list_id = [1,2,3]
      name_animal = ['cat','dog','mamal']









      share|improve this question













      I wanted to extract the value of a column given another column with id's of a different dataset.



      DF-1:



      ID  A       B
      1 cat 22
      2 dog 33
      3 mamal 44
      4 rat 55
      5 rabbit 66
      6 puppy 77


      DF-2:



      name   fav_animal
      x 1,2,3
      y 2,3
      z 3,4


      I wanted to see the fav animals of x in a new list say name_animal.



      code:



      #storing all the id's of x frist
      list_id =
      name_animal =
      for i in list_ids:
      name_animal.append(df1.loc[df1.id == i, 'A'].values.to_list()


      Output:



      list_id = [1,2,3]
      name_animal = ['cat','dog','mamal']






      python python-3.x pandas






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 21 '18 at 12:59









      pylearner

      341111




      341111
























          4 Answers
          4






          active

          oldest

          votes


















          2














          First check find fav_animal values with boolean indexing, next and iter is for return empty list if no name matched.



          a = next(iter(df2.loc[df2['name'] == 'x', 'fav_animal']), )


          Then split values and convert them to integers:



          list_id = list(map(int, a.split(',')))
          print (list_id)
          [1, 2, 3]


          And last filter by isin first DataFrame:



          name_animal = df1.loc[df1.ID.isin(list_id), 'A'].values.tolist()
          print (name_animal)
          ['cat', 'dog', 'mamal']





          share|improve this answer































            1














            You can use this function for example:



            def get_names(df, df2, name):
            indices = np.asarray(df2.loc[name].values[0].split(',')).astype(int)
            return indices.tolist(), df.loc[indices,:]['A'].tolist()


            So, for example if you want the fav_animals for name x:



            list_id, name_animal = get_names(df,df2, 'x')

            print(list_id)
            [1, 2, 3]

            print(name_animal)
            ['dog', 'mamal', 'rat']





            share|improve this answer































              1














              I think what you're looking for is this:



              df1 = pd.DataFrame({'ID':np.arange(1, 7),
              'A': ['cat', 'dog', 'mamal', 'rat', 'rabbit', 'puppy'],
              'B': [22, 33, 44, 55, 66, 77]})

              df2 = pd.DataFrame({'name': ['x', 'y', 'z'],
              'fav_animal': ['1,2,3', '2,3', '3,4']})

              df2.loc[df2.name == 'x', 'fav_animal'].str.split(',')[0]
              ['1', '2', '3']


              Returns a list of strings. So you need to convert values to integers using map function.



              mask = map(int, df2.loc[df2.name == 'x', 'fav_animal'].str.split(',')[0])

              df1.loc[df1.ID.isin(mask), 'A'].values.tolist()
              >['cat', 'dog', 'mamal']





              share|improve this answer





























                0














                Something like this?



                for i in df2.fav_animal.tolist():
                print(df1.loc[map(int, i.split(","))]["A"].tolist())


                Output:



                ['dog', 'mamal', 'rat']
                ['mamal', 'rat']
                ['rat', 'rabbit']


                Alternative:



                print([df1.loc[map(int, i.split(","))]["A"].tolist() for i in df2.fav_animal.tolist()])


                Output:



                [['dog', 'mamal', 'rat'], ['mamal', 'rat'], ['rat', 'rabbit']]





                share|improve this answer























                  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%2f53412580%2fhow-to-get-a-value-of-a-column-based-on-the-ids-given-from-another-table%23new-answer', 'question_page');
                  }
                  );

                  Post as a guest















                  Required, but never shown

























                  4 Answers
                  4






                  active

                  oldest

                  votes








                  4 Answers
                  4






                  active

                  oldest

                  votes









                  active

                  oldest

                  votes






                  active

                  oldest

                  votes









                  2














                  First check find fav_animal values with boolean indexing, next and iter is for return empty list if no name matched.



                  a = next(iter(df2.loc[df2['name'] == 'x', 'fav_animal']), )


                  Then split values and convert them to integers:



                  list_id = list(map(int, a.split(',')))
                  print (list_id)
                  [1, 2, 3]


                  And last filter by isin first DataFrame:



                  name_animal = df1.loc[df1.ID.isin(list_id), 'A'].values.tolist()
                  print (name_animal)
                  ['cat', 'dog', 'mamal']





                  share|improve this answer




























                    2














                    First check find fav_animal values with boolean indexing, next and iter is for return empty list if no name matched.



                    a = next(iter(df2.loc[df2['name'] == 'x', 'fav_animal']), )


                    Then split values and convert them to integers:



                    list_id = list(map(int, a.split(',')))
                    print (list_id)
                    [1, 2, 3]


                    And last filter by isin first DataFrame:



                    name_animal = df1.loc[df1.ID.isin(list_id), 'A'].values.tolist()
                    print (name_animal)
                    ['cat', 'dog', 'mamal']





                    share|improve this answer


























                      2












                      2








                      2






                      First check find fav_animal values with boolean indexing, next and iter is for return empty list if no name matched.



                      a = next(iter(df2.loc[df2['name'] == 'x', 'fav_animal']), )


                      Then split values and convert them to integers:



                      list_id = list(map(int, a.split(',')))
                      print (list_id)
                      [1, 2, 3]


                      And last filter by isin first DataFrame:



                      name_animal = df1.loc[df1.ID.isin(list_id), 'A'].values.tolist()
                      print (name_animal)
                      ['cat', 'dog', 'mamal']





                      share|improve this answer














                      First check find fav_animal values with boolean indexing, next and iter is for return empty list if no name matched.



                      a = next(iter(df2.loc[df2['name'] == 'x', 'fav_animal']), )


                      Then split values and convert them to integers:



                      list_id = list(map(int, a.split(',')))
                      print (list_id)
                      [1, 2, 3]


                      And last filter by isin first DataFrame:



                      name_animal = df1.loc[df1.ID.isin(list_id), 'A'].values.tolist()
                      print (name_animal)
                      ['cat', 'dog', 'mamal']






                      share|improve this answer














                      share|improve this answer



                      share|improve this answer








                      edited Nov 21 '18 at 13:15

























                      answered Nov 21 '18 at 13:07









                      jezrael

                      320k22259338




                      320k22259338

























                          1














                          You can use this function for example:



                          def get_names(df, df2, name):
                          indices = np.asarray(df2.loc[name].values[0].split(',')).astype(int)
                          return indices.tolist(), df.loc[indices,:]['A'].tolist()


                          So, for example if you want the fav_animals for name x:



                          list_id, name_animal = get_names(df,df2, 'x')

                          print(list_id)
                          [1, 2, 3]

                          print(name_animal)
                          ['dog', 'mamal', 'rat']





                          share|improve this answer




























                            1














                            You can use this function for example:



                            def get_names(df, df2, name):
                            indices = np.asarray(df2.loc[name].values[0].split(',')).astype(int)
                            return indices.tolist(), df.loc[indices,:]['A'].tolist()


                            So, for example if you want the fav_animals for name x:



                            list_id, name_animal = get_names(df,df2, 'x')

                            print(list_id)
                            [1, 2, 3]

                            print(name_animal)
                            ['dog', 'mamal', 'rat']





                            share|improve this answer


























                              1












                              1








                              1






                              You can use this function for example:



                              def get_names(df, df2, name):
                              indices = np.asarray(df2.loc[name].values[0].split(',')).astype(int)
                              return indices.tolist(), df.loc[indices,:]['A'].tolist()


                              So, for example if you want the fav_animals for name x:



                              list_id, name_animal = get_names(df,df2, 'x')

                              print(list_id)
                              [1, 2, 3]

                              print(name_animal)
                              ['dog', 'mamal', 'rat']





                              share|improve this answer














                              You can use this function for example:



                              def get_names(df, df2, name):
                              indices = np.asarray(df2.loc[name].values[0].split(',')).astype(int)
                              return indices.tolist(), df.loc[indices,:]['A'].tolist()


                              So, for example if you want the fav_animals for name x:



                              list_id, name_animal = get_names(df,df2, 'x')

                              print(list_id)
                              [1, 2, 3]

                              print(name_animal)
                              ['dog', 'mamal', 'rat']






                              share|improve this answer














                              share|improve this answer



                              share|improve this answer








                              edited Nov 21 '18 at 13:12

























                              answered Nov 21 '18 at 13:07









                              yatu

                              4,7321423




                              4,7321423























                                  1














                                  I think what you're looking for is this:



                                  df1 = pd.DataFrame({'ID':np.arange(1, 7),
                                  'A': ['cat', 'dog', 'mamal', 'rat', 'rabbit', 'puppy'],
                                  'B': [22, 33, 44, 55, 66, 77]})

                                  df2 = pd.DataFrame({'name': ['x', 'y', 'z'],
                                  'fav_animal': ['1,2,3', '2,3', '3,4']})

                                  df2.loc[df2.name == 'x', 'fav_animal'].str.split(',')[0]
                                  ['1', '2', '3']


                                  Returns a list of strings. So you need to convert values to integers using map function.



                                  mask = map(int, df2.loc[df2.name == 'x', 'fav_animal'].str.split(',')[0])

                                  df1.loc[df1.ID.isin(mask), 'A'].values.tolist()
                                  >['cat', 'dog', 'mamal']





                                  share|improve this answer


























                                    1














                                    I think what you're looking for is this:



                                    df1 = pd.DataFrame({'ID':np.arange(1, 7),
                                    'A': ['cat', 'dog', 'mamal', 'rat', 'rabbit', 'puppy'],
                                    'B': [22, 33, 44, 55, 66, 77]})

                                    df2 = pd.DataFrame({'name': ['x', 'y', 'z'],
                                    'fav_animal': ['1,2,3', '2,3', '3,4']})

                                    df2.loc[df2.name == 'x', 'fav_animal'].str.split(',')[0]
                                    ['1', '2', '3']


                                    Returns a list of strings. So you need to convert values to integers using map function.



                                    mask = map(int, df2.loc[df2.name == 'x', 'fav_animal'].str.split(',')[0])

                                    df1.loc[df1.ID.isin(mask), 'A'].values.tolist()
                                    >['cat', 'dog', 'mamal']





                                    share|improve this answer
























                                      1












                                      1








                                      1






                                      I think what you're looking for is this:



                                      df1 = pd.DataFrame({'ID':np.arange(1, 7),
                                      'A': ['cat', 'dog', 'mamal', 'rat', 'rabbit', 'puppy'],
                                      'B': [22, 33, 44, 55, 66, 77]})

                                      df2 = pd.DataFrame({'name': ['x', 'y', 'z'],
                                      'fav_animal': ['1,2,3', '2,3', '3,4']})

                                      df2.loc[df2.name == 'x', 'fav_animal'].str.split(',')[0]
                                      ['1', '2', '3']


                                      Returns a list of strings. So you need to convert values to integers using map function.



                                      mask = map(int, df2.loc[df2.name == 'x', 'fav_animal'].str.split(',')[0])

                                      df1.loc[df1.ID.isin(mask), 'A'].values.tolist()
                                      >['cat', 'dog', 'mamal']





                                      share|improve this answer












                                      I think what you're looking for is this:



                                      df1 = pd.DataFrame({'ID':np.arange(1, 7),
                                      'A': ['cat', 'dog', 'mamal', 'rat', 'rabbit', 'puppy'],
                                      'B': [22, 33, 44, 55, 66, 77]})

                                      df2 = pd.DataFrame({'name': ['x', 'y', 'z'],
                                      'fav_animal': ['1,2,3', '2,3', '3,4']})

                                      df2.loc[df2.name == 'x', 'fav_animal'].str.split(',')[0]
                                      ['1', '2', '3']


                                      Returns a list of strings. So you need to convert values to integers using map function.



                                      mask = map(int, df2.loc[df2.name == 'x', 'fav_animal'].str.split(',')[0])

                                      df1.loc[df1.ID.isin(mask), 'A'].values.tolist()
                                      >['cat', 'dog', 'mamal']






                                      share|improve this answer












                                      share|improve this answer



                                      share|improve this answer










                                      answered Nov 21 '18 at 13:18









                                      Mohit Motwani

                                      1,1111422




                                      1,1111422























                                          0














                                          Something like this?



                                          for i in df2.fav_animal.tolist():
                                          print(df1.loc[map(int, i.split(","))]["A"].tolist())


                                          Output:



                                          ['dog', 'mamal', 'rat']
                                          ['mamal', 'rat']
                                          ['rat', 'rabbit']


                                          Alternative:



                                          print([df1.loc[map(int, i.split(","))]["A"].tolist() for i in df2.fav_animal.tolist()])


                                          Output:



                                          [['dog', 'mamal', 'rat'], ['mamal', 'rat'], ['rat', 'rabbit']]





                                          share|improve this answer




























                                            0














                                            Something like this?



                                            for i in df2.fav_animal.tolist():
                                            print(df1.loc[map(int, i.split(","))]["A"].tolist())


                                            Output:



                                            ['dog', 'mamal', 'rat']
                                            ['mamal', 'rat']
                                            ['rat', 'rabbit']


                                            Alternative:



                                            print([df1.loc[map(int, i.split(","))]["A"].tolist() for i in df2.fav_animal.tolist()])


                                            Output:



                                            [['dog', 'mamal', 'rat'], ['mamal', 'rat'], ['rat', 'rabbit']]





                                            share|improve this answer


























                                              0












                                              0








                                              0






                                              Something like this?



                                              for i in df2.fav_animal.tolist():
                                              print(df1.loc[map(int, i.split(","))]["A"].tolist())


                                              Output:



                                              ['dog', 'mamal', 'rat']
                                              ['mamal', 'rat']
                                              ['rat', 'rabbit']


                                              Alternative:



                                              print([df1.loc[map(int, i.split(","))]["A"].tolist() for i in df2.fav_animal.tolist()])


                                              Output:



                                              [['dog', 'mamal', 'rat'], ['mamal', 'rat'], ['rat', 'rabbit']]





                                              share|improve this answer














                                              Something like this?



                                              for i in df2.fav_animal.tolist():
                                              print(df1.loc[map(int, i.split(","))]["A"].tolist())


                                              Output:



                                              ['dog', 'mamal', 'rat']
                                              ['mamal', 'rat']
                                              ['rat', 'rabbit']


                                              Alternative:



                                              print([df1.loc[map(int, i.split(","))]["A"].tolist() for i in df2.fav_animal.tolist()])


                                              Output:



                                              [['dog', 'mamal', 'rat'], ['mamal', 'rat'], ['rat', 'rabbit']]






                                              share|improve this answer














                                              share|improve this answer



                                              share|improve this answer








                                              edited Nov 21 '18 at 13:24

























                                              answered Nov 21 '18 at 13:14









                                              Srce Cde

                                              1,136511




                                              1,136511






























                                                  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%2f53412580%2fhow-to-get-a-value-of-a-column-based-on-the-ids-given-from-another-table%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

                                                  404 Error Contact Form 7 ajax form submitting

                                                  How to know if a Active Directory user can login interactively

                                                  Refactoring coordinates for Minecraft Pi buildings written in Python