Split a list of values into columns of a dataframe?












2












$begingroup$


I am new to python and stuck at a particular problem involving dataframes.



Sample Image clipped from Spyder



The image has a sample column, however the data is not consistent. There are also some floats and NAN. I need these to be split across columns. That is each unique value becomes a column in the df.



Any insights?










share|improve this question









$endgroup$












  • $begingroup$
    Possible duplicate of How to binary encode multi-valued categorical variable from Pandas dataframe?
    $endgroup$
    – Emre
    May 17 '16 at 6:11
















2












$begingroup$


I am new to python and stuck at a particular problem involving dataframes.



Sample Image clipped from Spyder



The image has a sample column, however the data is not consistent. There are also some floats and NAN. I need these to be split across columns. That is each unique value becomes a column in the df.



Any insights?










share|improve this question









$endgroup$












  • $begingroup$
    Possible duplicate of How to binary encode multi-valued categorical variable from Pandas dataframe?
    $endgroup$
    – Emre
    May 17 '16 at 6:11














2












2








2


4



$begingroup$


I am new to python and stuck at a particular problem involving dataframes.



Sample Image clipped from Spyder



The image has a sample column, however the data is not consistent. There are also some floats and NAN. I need these to be split across columns. That is each unique value becomes a column in the df.



Any insights?










share|improve this question









$endgroup$




I am new to python and stuck at a particular problem involving dataframes.



Sample Image clipped from Spyder



The image has a sample column, however the data is not consistent. There are also some floats and NAN. I need these to be split across columns. That is each unique value becomes a column in the df.



Any insights?







python pandas






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked May 17 '16 at 1:37









DrjDrj

2771416




2771416












  • $begingroup$
    Possible duplicate of How to binary encode multi-valued categorical variable from Pandas dataframe?
    $endgroup$
    – Emre
    May 17 '16 at 6:11


















  • $begingroup$
    Possible duplicate of How to binary encode multi-valued categorical variable from Pandas dataframe?
    $endgroup$
    – Emre
    May 17 '16 at 6:11
















$begingroup$
Possible duplicate of How to binary encode multi-valued categorical variable from Pandas dataframe?
$endgroup$
– Emre
May 17 '16 at 6:11




$begingroup$
Possible duplicate of How to binary encode multi-valued categorical variable from Pandas dataframe?
$endgroup$
– Emre
May 17 '16 at 6:11










3 Answers
3






active

oldest

votes


















6












$begingroup$

It looks like you're trying to "featurize" the genre column.



df = pandas.Series([('Adventure', 'Drama', 'Fantasy'), ('Comedy', 'Family'), ('Drama', 'Comedy', 'Romance'), (['Drama']), 
(['Documentary']), ('Adventure', 'Biography', 'Drama', 'Thriller')]).apply(frozenset).to_frame(name='genre')
for genre in frozenset.union(*df.genre):
df[genre] = df.apply(lambda _: int(genre in _.genre), axis=1)


The output:



| row | genre                                   | Romance | Documentary | Thriller | Biography | Family | Drama | Comedy | Adventure | Fantasy |
|-----|-----------------------------------------|---------|-------------|----------|-----------|--------|-------|--------|-----------|---------|
| 0 | (Drama, Adventure, Fantasy) | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 1 |
| 1 | (Comedy, Family) | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 |
| 2 | (Drama, Comedy, Romance) | 1 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 |
| 3 | (Drama) | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 |
| 4 | (Documentary) | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| 5 | (Drama, Biography, Adventure, Thriller) | 0 | 0 | 1 | 1 | 0 | 1 | 0 | 1 | 0 |





share|improve this answer









$endgroup$









  • 1




    $begingroup$
    @Drj If this answers your question, please tick it off, otherwise indicate what's wrong. This helps keep our site useful.
    $endgroup$
    – Emre
    May 20 '16 at 21:48





















1












$begingroup$

If you want counts, instead of the Boolean values, you can try like this.



df = pandas.Series([('Adventure', 'Drama', 'Fantasy','Fantasy'), ('Comedy', 'Family'), ('Drama', 'Comedy', 'Romance'), (['Drama']), 
(['Documentary','Documentary']), ('Adventure','Adventure' ,'Biography', 'Drama', 'Thriller')]).apply(list).to_frame(name='genre')
for genre in set.union(*df.genre.apply(set)):
df[genre] = df.apply(lambda _: int(_.genre.count(genre)), axis=1)





share|improve this answer











$endgroup$





















    1












    $begingroup$

    I tried it first with pandas before but it was just a pain to achieve. Use MultiLabelBinarizer from the scikit-learn package:



    import pandas
    from sklearn.preprocessing import MultiLabelBinarizer


    # Binarise labels
    mlb = MultiLabelBinarizer()
    expandedLabelData = mlb.fit_transform(data["genre"])
    labelClasses = mlb.classes_


    # Create a pandas.DataFrame from our output
    expandedLabels = pandas.DataFrame(expandedLabelData, columns=labelClasses)





    share|improve this answer











    $endgroup$













      Your Answer





      StackExchange.ifUsing("editor", function () {
      return StackExchange.using("mathjaxEditing", function () {
      StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
      StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["$", "$"], ["\\(","\\)"]]);
      });
      });
      }, "mathjax-editing");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "557"
      };
      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: false,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: null,
      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%2fdatascience.stackexchange.com%2fquestions%2f11797%2fsplit-a-list-of-values-into-columns-of-a-dataframe%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









      6












      $begingroup$

      It looks like you're trying to "featurize" the genre column.



      df = pandas.Series([('Adventure', 'Drama', 'Fantasy'), ('Comedy', 'Family'), ('Drama', 'Comedy', 'Romance'), (['Drama']), 
      (['Documentary']), ('Adventure', 'Biography', 'Drama', 'Thriller')]).apply(frozenset).to_frame(name='genre')
      for genre in frozenset.union(*df.genre):
      df[genre] = df.apply(lambda _: int(genre in _.genre), axis=1)


      The output:



      | row | genre                                   | Romance | Documentary | Thriller | Biography | Family | Drama | Comedy | Adventure | Fantasy |
      |-----|-----------------------------------------|---------|-------------|----------|-----------|--------|-------|--------|-----------|---------|
      | 0 | (Drama, Adventure, Fantasy) | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 1 |
      | 1 | (Comedy, Family) | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 |
      | 2 | (Drama, Comedy, Romance) | 1 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 |
      | 3 | (Drama) | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 |
      | 4 | (Documentary) | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
      | 5 | (Drama, Biography, Adventure, Thriller) | 0 | 0 | 1 | 1 | 0 | 1 | 0 | 1 | 0 |





      share|improve this answer









      $endgroup$









      • 1




        $begingroup$
        @Drj If this answers your question, please tick it off, otherwise indicate what's wrong. This helps keep our site useful.
        $endgroup$
        – Emre
        May 20 '16 at 21:48


















      6












      $begingroup$

      It looks like you're trying to "featurize" the genre column.



      df = pandas.Series([('Adventure', 'Drama', 'Fantasy'), ('Comedy', 'Family'), ('Drama', 'Comedy', 'Romance'), (['Drama']), 
      (['Documentary']), ('Adventure', 'Biography', 'Drama', 'Thriller')]).apply(frozenset).to_frame(name='genre')
      for genre in frozenset.union(*df.genre):
      df[genre] = df.apply(lambda _: int(genre in _.genre), axis=1)


      The output:



      | row | genre                                   | Romance | Documentary | Thriller | Biography | Family | Drama | Comedy | Adventure | Fantasy |
      |-----|-----------------------------------------|---------|-------------|----------|-----------|--------|-------|--------|-----------|---------|
      | 0 | (Drama, Adventure, Fantasy) | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 1 |
      | 1 | (Comedy, Family) | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 |
      | 2 | (Drama, Comedy, Romance) | 1 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 |
      | 3 | (Drama) | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 |
      | 4 | (Documentary) | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
      | 5 | (Drama, Biography, Adventure, Thriller) | 0 | 0 | 1 | 1 | 0 | 1 | 0 | 1 | 0 |





      share|improve this answer









      $endgroup$









      • 1




        $begingroup$
        @Drj If this answers your question, please tick it off, otherwise indicate what's wrong. This helps keep our site useful.
        $endgroup$
        – Emre
        May 20 '16 at 21:48
















      6












      6








      6





      $begingroup$

      It looks like you're trying to "featurize" the genre column.



      df = pandas.Series([('Adventure', 'Drama', 'Fantasy'), ('Comedy', 'Family'), ('Drama', 'Comedy', 'Romance'), (['Drama']), 
      (['Documentary']), ('Adventure', 'Biography', 'Drama', 'Thriller')]).apply(frozenset).to_frame(name='genre')
      for genre in frozenset.union(*df.genre):
      df[genre] = df.apply(lambda _: int(genre in _.genre), axis=1)


      The output:



      | row | genre                                   | Romance | Documentary | Thriller | Biography | Family | Drama | Comedy | Adventure | Fantasy |
      |-----|-----------------------------------------|---------|-------------|----------|-----------|--------|-------|--------|-----------|---------|
      | 0 | (Drama, Adventure, Fantasy) | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 1 |
      | 1 | (Comedy, Family) | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 |
      | 2 | (Drama, Comedy, Romance) | 1 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 |
      | 3 | (Drama) | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 |
      | 4 | (Documentary) | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
      | 5 | (Drama, Biography, Adventure, Thriller) | 0 | 0 | 1 | 1 | 0 | 1 | 0 | 1 | 0 |





      share|improve this answer









      $endgroup$



      It looks like you're trying to "featurize" the genre column.



      df = pandas.Series([('Adventure', 'Drama', 'Fantasy'), ('Comedy', 'Family'), ('Drama', 'Comedy', 'Romance'), (['Drama']), 
      (['Documentary']), ('Adventure', 'Biography', 'Drama', 'Thriller')]).apply(frozenset).to_frame(name='genre')
      for genre in frozenset.union(*df.genre):
      df[genre] = df.apply(lambda _: int(genre in _.genre), axis=1)


      The output:



      | row | genre                                   | Romance | Documentary | Thriller | Biography | Family | Drama | Comedy | Adventure | Fantasy |
      |-----|-----------------------------------------|---------|-------------|----------|-----------|--------|-------|--------|-----------|---------|
      | 0 | (Drama, Adventure, Fantasy) | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 1 |
      | 1 | (Comedy, Family) | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 |
      | 2 | (Drama, Comedy, Romance) | 1 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 |
      | 3 | (Drama) | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 |
      | 4 | (Documentary) | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
      | 5 | (Drama, Biography, Adventure, Thriller) | 0 | 0 | 1 | 1 | 0 | 1 | 0 | 1 | 0 |






      share|improve this answer












      share|improve this answer



      share|improve this answer










      answered May 17 '16 at 6:08









      EmreEmre

      8,50011935




      8,50011935








      • 1




        $begingroup$
        @Drj If this answers your question, please tick it off, otherwise indicate what's wrong. This helps keep our site useful.
        $endgroup$
        – Emre
        May 20 '16 at 21:48
















      • 1




        $begingroup$
        @Drj If this answers your question, please tick it off, otherwise indicate what's wrong. This helps keep our site useful.
        $endgroup$
        – Emre
        May 20 '16 at 21:48










      1




      1




      $begingroup$
      @Drj If this answers your question, please tick it off, otherwise indicate what's wrong. This helps keep our site useful.
      $endgroup$
      – Emre
      May 20 '16 at 21:48






      $begingroup$
      @Drj If this answers your question, please tick it off, otherwise indicate what's wrong. This helps keep our site useful.
      $endgroup$
      – Emre
      May 20 '16 at 21:48













      1












      $begingroup$

      If you want counts, instead of the Boolean values, you can try like this.



      df = pandas.Series([('Adventure', 'Drama', 'Fantasy','Fantasy'), ('Comedy', 'Family'), ('Drama', 'Comedy', 'Romance'), (['Drama']), 
      (['Documentary','Documentary']), ('Adventure','Adventure' ,'Biography', 'Drama', 'Thriller')]).apply(list).to_frame(name='genre')
      for genre in set.union(*df.genre.apply(set)):
      df[genre] = df.apply(lambda _: int(_.genre.count(genre)), axis=1)





      share|improve this answer











      $endgroup$


















        1












        $begingroup$

        If you want counts, instead of the Boolean values, you can try like this.



        df = pandas.Series([('Adventure', 'Drama', 'Fantasy','Fantasy'), ('Comedy', 'Family'), ('Drama', 'Comedy', 'Romance'), (['Drama']), 
        (['Documentary','Documentary']), ('Adventure','Adventure' ,'Biography', 'Drama', 'Thriller')]).apply(list).to_frame(name='genre')
        for genre in set.union(*df.genre.apply(set)):
        df[genre] = df.apply(lambda _: int(_.genre.count(genre)), axis=1)





        share|improve this answer











        $endgroup$
















          1












          1








          1





          $begingroup$

          If you want counts, instead of the Boolean values, you can try like this.



          df = pandas.Series([('Adventure', 'Drama', 'Fantasy','Fantasy'), ('Comedy', 'Family'), ('Drama', 'Comedy', 'Romance'), (['Drama']), 
          (['Documentary','Documentary']), ('Adventure','Adventure' ,'Biography', 'Drama', 'Thriller')]).apply(list).to_frame(name='genre')
          for genre in set.union(*df.genre.apply(set)):
          df[genre] = df.apply(lambda _: int(_.genre.count(genre)), axis=1)





          share|improve this answer











          $endgroup$



          If you want counts, instead of the Boolean values, you can try like this.



          df = pandas.Series([('Adventure', 'Drama', 'Fantasy','Fantasy'), ('Comedy', 'Family'), ('Drama', 'Comedy', 'Romance'), (['Drama']), 
          (['Documentary','Documentary']), ('Adventure','Adventure' ,'Biography', 'Drama', 'Thriller')]).apply(list).to_frame(name='genre')
          for genre in set.union(*df.genre.apply(set)):
          df[genre] = df.apply(lambda _: int(_.genre.count(genre)), axis=1)






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Apr 4 '18 at 13:57









          Stephen Rauch

          1,52751129




          1,52751129










          answered Apr 4 '18 at 10:57









          TARUN KUMARTARUN KUMAR

          113




          113























              1












              $begingroup$

              I tried it first with pandas before but it was just a pain to achieve. Use MultiLabelBinarizer from the scikit-learn package:



              import pandas
              from sklearn.preprocessing import MultiLabelBinarizer


              # Binarise labels
              mlb = MultiLabelBinarizer()
              expandedLabelData = mlb.fit_transform(data["genre"])
              labelClasses = mlb.classes_


              # Create a pandas.DataFrame from our output
              expandedLabels = pandas.DataFrame(expandedLabelData, columns=labelClasses)





              share|improve this answer











              $endgroup$


















                1












                $begingroup$

                I tried it first with pandas before but it was just a pain to achieve. Use MultiLabelBinarizer from the scikit-learn package:



                import pandas
                from sklearn.preprocessing import MultiLabelBinarizer


                # Binarise labels
                mlb = MultiLabelBinarizer()
                expandedLabelData = mlb.fit_transform(data["genre"])
                labelClasses = mlb.classes_


                # Create a pandas.DataFrame from our output
                expandedLabels = pandas.DataFrame(expandedLabelData, columns=labelClasses)





                share|improve this answer











                $endgroup$
















                  1












                  1








                  1





                  $begingroup$

                  I tried it first with pandas before but it was just a pain to achieve. Use MultiLabelBinarizer from the scikit-learn package:



                  import pandas
                  from sklearn.preprocessing import MultiLabelBinarizer


                  # Binarise labels
                  mlb = MultiLabelBinarizer()
                  expandedLabelData = mlb.fit_transform(data["genre"])
                  labelClasses = mlb.classes_


                  # Create a pandas.DataFrame from our output
                  expandedLabels = pandas.DataFrame(expandedLabelData, columns=labelClasses)





                  share|improve this answer











                  $endgroup$



                  I tried it first with pandas before but it was just a pain to achieve. Use MultiLabelBinarizer from the scikit-learn package:



                  import pandas
                  from sklearn.preprocessing import MultiLabelBinarizer


                  # Binarise labels
                  mlb = MultiLabelBinarizer()
                  expandedLabelData = mlb.fit_transform(data["genre"])
                  labelClasses = mlb.classes_


                  # Create a pandas.DataFrame from our output
                  expandedLabels = pandas.DataFrame(expandedLabelData, columns=labelClasses)






                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited 24 mins ago

























                  answered Nov 26 '18 at 23:12









                  holzkohlengrillholzkohlengrill

                  1113




                  1113






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Data Science Stack Exchange!


                      • 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.


                      Use MathJax to format equations. MathJax reference.


                      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%2fdatascience.stackexchange.com%2fquestions%2f11797%2fsplit-a-list-of-values-into-columns-of-a-dataframe%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

                      How to label and detect the document text images

                      Vallis Paradisi

                      Tabula Rosettana