Read data as list in python?












1















     x       y
[133,28,23] female
[157,22,87] male
[160,33,77] male
[122,87,20] female
[120,22,20] female


This is the data that i have in my book.csv file.



>>fd=pandas.read_csv("C://users/admin/Desktop/Book1.csv")
>>l1=[h for h in fd.x]


After following commands, l1 stores this value:



['[133,28,23]', '[157,22,87]', '[160,33,77]', '[122,87,20]', '[120,22,20]']


The following output is string in list format, but i want nested list like this:



[[133,28,23],[157,22,87],[160,33,77],[122,87,20],[120,22,20]]


What changes do I need to make?










share|improve this question

























  • data.x.tolist()

    – iamklaus
    Nov 13 '18 at 14:48











  • Possible duplicate of Convert string representation of list to list

    – ritlew
    Nov 13 '18 at 14:50











  • still the same >>> fd.x.tolist() ['[133,28,23]', '[157,22,87]', '[160,33,77]', '[122,87,20]', '[120,22,20]']

    – Rusher
    Nov 13 '18 at 14:50


















1















     x       y
[133,28,23] female
[157,22,87] male
[160,33,77] male
[122,87,20] female
[120,22,20] female


This is the data that i have in my book.csv file.



>>fd=pandas.read_csv("C://users/admin/Desktop/Book1.csv")
>>l1=[h for h in fd.x]


After following commands, l1 stores this value:



['[133,28,23]', '[157,22,87]', '[160,33,77]', '[122,87,20]', '[120,22,20]']


The following output is string in list format, but i want nested list like this:



[[133,28,23],[157,22,87],[160,33,77],[122,87,20],[120,22,20]]


What changes do I need to make?










share|improve this question

























  • data.x.tolist()

    – iamklaus
    Nov 13 '18 at 14:48











  • Possible duplicate of Convert string representation of list to list

    – ritlew
    Nov 13 '18 at 14:50











  • still the same >>> fd.x.tolist() ['[133,28,23]', '[157,22,87]', '[160,33,77]', '[122,87,20]', '[120,22,20]']

    – Rusher
    Nov 13 '18 at 14:50
















1












1








1








     x       y
[133,28,23] female
[157,22,87] male
[160,33,77] male
[122,87,20] female
[120,22,20] female


This is the data that i have in my book.csv file.



>>fd=pandas.read_csv("C://users/admin/Desktop/Book1.csv")
>>l1=[h for h in fd.x]


After following commands, l1 stores this value:



['[133,28,23]', '[157,22,87]', '[160,33,77]', '[122,87,20]', '[120,22,20]']


The following output is string in list format, but i want nested list like this:



[[133,28,23],[157,22,87],[160,33,77],[122,87,20],[120,22,20]]


What changes do I need to make?










share|improve this question
















     x       y
[133,28,23] female
[157,22,87] male
[160,33,77] male
[122,87,20] female
[120,22,20] female


This is the data that i have in my book.csv file.



>>fd=pandas.read_csv("C://users/admin/Desktop/Book1.csv")
>>l1=[h for h in fd.x]


After following commands, l1 stores this value:



['[133,28,23]', '[157,22,87]', '[160,33,77]', '[122,87,20]', '[120,22,20]']


The following output is string in list format, but i want nested list like this:



[[133,28,23],[157,22,87],[160,33,77],[122,87,20],[120,22,20]]


What changes do I need to make?







python pandas list csv






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 13 '18 at 15:21









ritlew

853411




853411










asked Nov 13 '18 at 14:44









RusherRusher

111




111













  • data.x.tolist()

    – iamklaus
    Nov 13 '18 at 14:48











  • Possible duplicate of Convert string representation of list to list

    – ritlew
    Nov 13 '18 at 14:50











  • still the same >>> fd.x.tolist() ['[133,28,23]', '[157,22,87]', '[160,33,77]', '[122,87,20]', '[120,22,20]']

    – Rusher
    Nov 13 '18 at 14:50





















  • data.x.tolist()

    – iamklaus
    Nov 13 '18 at 14:48











  • Possible duplicate of Convert string representation of list to list

    – ritlew
    Nov 13 '18 at 14:50











  • still the same >>> fd.x.tolist() ['[133,28,23]', '[157,22,87]', '[160,33,77]', '[122,87,20]', '[120,22,20]']

    – Rusher
    Nov 13 '18 at 14:50



















data.x.tolist()

– iamklaus
Nov 13 '18 at 14:48





data.x.tolist()

– iamklaus
Nov 13 '18 at 14:48













Possible duplicate of Convert string representation of list to list

– ritlew
Nov 13 '18 at 14:50





Possible duplicate of Convert string representation of list to list

– ritlew
Nov 13 '18 at 14:50













still the same >>> fd.x.tolist() ['[133,28,23]', '[157,22,87]', '[160,33,77]', '[122,87,20]', '[120,22,20]']

– Rusher
Nov 13 '18 at 14:50







still the same >>> fd.x.tolist() ['[133,28,23]', '[157,22,87]', '[160,33,77]', '[122,87,20]', '[120,22,20]']

– Rusher
Nov 13 '18 at 14:50














3 Answers
3






active

oldest

votes


















2














You could do the following, using ast.literal_eval:



import pandas as pd
import ast

data = [['[133,28,23]', 'female'],
['[157,22,87]', 'male'],
['[160,33,77]', 'male'],
['[122,87,20]', 'female'],
['[120,22,20]', 'female']]

df = pd.DataFrame(data=data, columns=['x', 'y'])
df['x'] = df['x'].apply(ast.literal_eval)
result = df['x'].tolist()

print(result)


Output



[[133, 28, 23], [157, 22, 87], [160, 33, 77], [122, 87, 20], [120, 22, 20]]





share|improve this answer































    0














    You can use json:



    >> import json
    >> fd=pandas.read_csv("C://users/admin/Desktop/Book1.csv")
    >> l1=[json.loads(h) for h in fd.x]
    [[133,28,23],[157,22,87],[160,33,77],[122,87,20],[120,22,20]]


    Or ast



    >> import ast
    >> fd=pandas.read_csv("C://users/admin/Desktop/Book1.csv")
    >> l1=[ast.literal_eval(h) for h in fd.x]
    >> [[133,28,23],[157,22,87],[160,33,77],[122,87,20],[120,22,20]]





    share|improve this answer































      0














      One simple way, if you don't want to resort to ast (for example to avoid parsing something that is not a list):



      from io import StringIO

      inp = """ x y
      [133,28,23] female
      [157,22,87] male
      [160,33,77] male
      [122,87,20] female
      [120,22,20] female"""

      # Read data
      df = pd.read_csv(StringIO(inp), delim_whitespace=True, header=0)
      # Remove brackets, split and convert to int
      df.x = df.x.map(lambda el: list(map(int, el.strip()[1:-1].split(','))))
      # Print
      l1 = [h for h in df.x]
      print(l1)


      Output:



      [[133, 28, 23], [157, 22, 87], [160, 33, 77], [122, 87, 20], [120, 22, 20]]





      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%2f53283513%2fread-data-as-list-in-python%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














        You could do the following, using ast.literal_eval:



        import pandas as pd
        import ast

        data = [['[133,28,23]', 'female'],
        ['[157,22,87]', 'male'],
        ['[160,33,77]', 'male'],
        ['[122,87,20]', 'female'],
        ['[120,22,20]', 'female']]

        df = pd.DataFrame(data=data, columns=['x', 'y'])
        df['x'] = df['x'].apply(ast.literal_eval)
        result = df['x'].tolist()

        print(result)


        Output



        [[133, 28, 23], [157, 22, 87], [160, 33, 77], [122, 87, 20], [120, 22, 20]]





        share|improve this answer




























          2














          You could do the following, using ast.literal_eval:



          import pandas as pd
          import ast

          data = [['[133,28,23]', 'female'],
          ['[157,22,87]', 'male'],
          ['[160,33,77]', 'male'],
          ['[122,87,20]', 'female'],
          ['[120,22,20]', 'female']]

          df = pd.DataFrame(data=data, columns=['x', 'y'])
          df['x'] = df['x'].apply(ast.literal_eval)
          result = df['x'].tolist()

          print(result)


          Output



          [[133, 28, 23], [157, 22, 87], [160, 33, 77], [122, 87, 20], [120, 22, 20]]





          share|improve this answer


























            2












            2








            2







            You could do the following, using ast.literal_eval:



            import pandas as pd
            import ast

            data = [['[133,28,23]', 'female'],
            ['[157,22,87]', 'male'],
            ['[160,33,77]', 'male'],
            ['[122,87,20]', 'female'],
            ['[120,22,20]', 'female']]

            df = pd.DataFrame(data=data, columns=['x', 'y'])
            df['x'] = df['x'].apply(ast.literal_eval)
            result = df['x'].tolist()

            print(result)


            Output



            [[133, 28, 23], [157, 22, 87], [160, 33, 77], [122, 87, 20], [120, 22, 20]]





            share|improve this answer













            You could do the following, using ast.literal_eval:



            import pandas as pd
            import ast

            data = [['[133,28,23]', 'female'],
            ['[157,22,87]', 'male'],
            ['[160,33,77]', 'male'],
            ['[122,87,20]', 'female'],
            ['[120,22,20]', 'female']]

            df = pd.DataFrame(data=data, columns=['x', 'y'])
            df['x'] = df['x'].apply(ast.literal_eval)
            result = df['x'].tolist()

            print(result)


            Output



            [[133, 28, 23], [157, 22, 87], [160, 33, 77], [122, 87, 20], [120, 22, 20]]






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Nov 13 '18 at 14:51









            Daniel MesejoDaniel Mesejo

            16.7k21430




            16.7k21430

























                0














                You can use json:



                >> import json
                >> fd=pandas.read_csv("C://users/admin/Desktop/Book1.csv")
                >> l1=[json.loads(h) for h in fd.x]
                [[133,28,23],[157,22,87],[160,33,77],[122,87,20],[120,22,20]]


                Or ast



                >> import ast
                >> fd=pandas.read_csv("C://users/admin/Desktop/Book1.csv")
                >> l1=[ast.literal_eval(h) for h in fd.x]
                >> [[133,28,23],[157,22,87],[160,33,77],[122,87,20],[120,22,20]]





                share|improve this answer




























                  0














                  You can use json:



                  >> import json
                  >> fd=pandas.read_csv("C://users/admin/Desktop/Book1.csv")
                  >> l1=[json.loads(h) for h in fd.x]
                  [[133,28,23],[157,22,87],[160,33,77],[122,87,20],[120,22,20]]


                  Or ast



                  >> import ast
                  >> fd=pandas.read_csv("C://users/admin/Desktop/Book1.csv")
                  >> l1=[ast.literal_eval(h) for h in fd.x]
                  >> [[133,28,23],[157,22,87],[160,33,77],[122,87,20],[120,22,20]]





                  share|improve this answer


























                    0












                    0








                    0







                    You can use json:



                    >> import json
                    >> fd=pandas.read_csv("C://users/admin/Desktop/Book1.csv")
                    >> l1=[json.loads(h) for h in fd.x]
                    [[133,28,23],[157,22,87],[160,33,77],[122,87,20],[120,22,20]]


                    Or ast



                    >> import ast
                    >> fd=pandas.read_csv("C://users/admin/Desktop/Book1.csv")
                    >> l1=[ast.literal_eval(h) for h in fd.x]
                    >> [[133,28,23],[157,22,87],[160,33,77],[122,87,20],[120,22,20]]





                    share|improve this answer













                    You can use json:



                    >> import json
                    >> fd=pandas.read_csv("C://users/admin/Desktop/Book1.csv")
                    >> l1=[json.loads(h) for h in fd.x]
                    [[133,28,23],[157,22,87],[160,33,77],[122,87,20],[120,22,20]]


                    Or ast



                    >> import ast
                    >> fd=pandas.read_csv("C://users/admin/Desktop/Book1.csv")
                    >> l1=[ast.literal_eval(h) for h in fd.x]
                    >> [[133,28,23],[157,22,87],[160,33,77],[122,87,20],[120,22,20]]






                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Nov 13 '18 at 14:52









                    HecvdHecvd

                    5471522




                    5471522























                        0














                        One simple way, if you don't want to resort to ast (for example to avoid parsing something that is not a list):



                        from io import StringIO

                        inp = """ x y
                        [133,28,23] female
                        [157,22,87] male
                        [160,33,77] male
                        [122,87,20] female
                        [120,22,20] female"""

                        # Read data
                        df = pd.read_csv(StringIO(inp), delim_whitespace=True, header=0)
                        # Remove brackets, split and convert to int
                        df.x = df.x.map(lambda el: list(map(int, el.strip()[1:-1].split(','))))
                        # Print
                        l1 = [h for h in df.x]
                        print(l1)


                        Output:



                        [[133, 28, 23], [157, 22, 87], [160, 33, 77], [122, 87, 20], [120, 22, 20]]





                        share|improve this answer




























                          0














                          One simple way, if you don't want to resort to ast (for example to avoid parsing something that is not a list):



                          from io import StringIO

                          inp = """ x y
                          [133,28,23] female
                          [157,22,87] male
                          [160,33,77] male
                          [122,87,20] female
                          [120,22,20] female"""

                          # Read data
                          df = pd.read_csv(StringIO(inp), delim_whitespace=True, header=0)
                          # Remove brackets, split and convert to int
                          df.x = df.x.map(lambda el: list(map(int, el.strip()[1:-1].split(','))))
                          # Print
                          l1 = [h for h in df.x]
                          print(l1)


                          Output:



                          [[133, 28, 23], [157, 22, 87], [160, 33, 77], [122, 87, 20], [120, 22, 20]]





                          share|improve this answer


























                            0












                            0








                            0







                            One simple way, if you don't want to resort to ast (for example to avoid parsing something that is not a list):



                            from io import StringIO

                            inp = """ x y
                            [133,28,23] female
                            [157,22,87] male
                            [160,33,77] male
                            [122,87,20] female
                            [120,22,20] female"""

                            # Read data
                            df = pd.read_csv(StringIO(inp), delim_whitespace=True, header=0)
                            # Remove brackets, split and convert to int
                            df.x = df.x.map(lambda el: list(map(int, el.strip()[1:-1].split(','))))
                            # Print
                            l1 = [h for h in df.x]
                            print(l1)


                            Output:



                            [[133, 28, 23], [157, 22, 87], [160, 33, 77], [122, 87, 20], [120, 22, 20]]





                            share|improve this answer













                            One simple way, if you don't want to resort to ast (for example to avoid parsing something that is not a list):



                            from io import StringIO

                            inp = """ x y
                            [133,28,23] female
                            [157,22,87] male
                            [160,33,77] male
                            [122,87,20] female
                            [120,22,20] female"""

                            # Read data
                            df = pd.read_csv(StringIO(inp), delim_whitespace=True, header=0)
                            # Remove brackets, split and convert to int
                            df.x = df.x.map(lambda el: list(map(int, el.strip()[1:-1].split(','))))
                            # Print
                            l1 = [h for h in df.x]
                            print(l1)


                            Output:



                            [[133, 28, 23], [157, 22, 87], [160, 33, 77], [122, 87, 20], [120, 22, 20]]






                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Nov 13 '18 at 14:55









                            jdehesajdehesa

                            23.2k43352




                            23.2k43352






























                                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%2f53283513%2fread-data-as-list-in-python%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

                                The Sandy Post

                                Danny Elfman

                                Pages that link to "Head v. Amoskeag Manufacturing Co."