is there a simpler way to group and count with python?Calling an external command in PythonWhat are metaclasses in Python?Is there a way to run Python on Android?Finding the index of an item given a list containing it in PythonDifference between append vs. extend list methods in PythonHow can I safely create a nested directory in Python?Does Python have a ternary conditional operator?How to get the current time in PythonDoes Python have a string 'contains' substring method?“Large data” work flows using pandas

If the Dominion rule using their Jem'Hadar troops, why is their life expectancy so low?

How to split IPA spelling into syllables

Why doesn't Gödel's incompleteness theorem apply to false statements?

What is this high flying aircraft over Pennsylvania?

A seasonal riddle

Put the phone down / Put down the phone

Turning a hard to access nut?

Is divisi notation needed for brass or woodwind in an orchestra?

How to get directions in deep space?

Not hide and seek

New Order #2: Turn My Way

Do people actually use the word "kaputt" in conversation?

Sort with assumptions

Checking @@ROWCOUNT failing

Why didn’t Eve recognize the little cockroach as a living organism?

"Marked down as someone wanting to sell shares." What does that mean?

Center page as a whole without centering each element individually

Derivative of an interpolated function

Why does a 97 / 92 key piano exist by Bosendorfer?

Should a narrator ever describe things based on a character's view instead of facts?

Highest stage count that are used one right after the other?

Is there any common country to visit for persons holding UK and Schengen visas?

Error in master's thesis, I do not know what to do

"Oh no!" in Latin



is there a simpler way to group and count with python?


Calling an external command in PythonWhat are metaclasses in Python?Is there a way to run Python on Android?Finding the index of an item given a list containing it in PythonDifference between append vs. extend list methods in PythonHow can I safely create a nested directory in Python?Does Python have a ternary conditional operator?How to get the current time in PythonDoes Python have a string 'contains' substring method?“Large data” work flows using pandas













0















I am grouping and counting a set of data.



df = pd.DataFrame('key': ['A', 'B', 'A'],
'data': np.ones(3,))
df.groupby('key').count()


outputs



 data
key
A 2
B 1


The piece of code above works though, I wonder if there is a simpler one.



'data': np.ones(3,) seems to be a placeholder and indispensable.



pd.DataFrame(['A', 'B', 'A']).groupby(0).count()


outputs



A
B


My question is, is there a simpler way to do this, produce the count of 'A' and 'B' respectively, without something like 'data': np.ones(3,) ?



It doesn't have to be a pandas method, numpy or python native function are also appreciated.










share|improve this question



















  • 3





    df.key.value_counts()?

    – coldspeed
    Mar 7 at 0:23
















0















I am grouping and counting a set of data.



df = pd.DataFrame('key': ['A', 'B', 'A'],
'data': np.ones(3,))
df.groupby('key').count()


outputs



 data
key
A 2
B 1


The piece of code above works though, I wonder if there is a simpler one.



'data': np.ones(3,) seems to be a placeholder and indispensable.



pd.DataFrame(['A', 'B', 'A']).groupby(0).count()


outputs



A
B


My question is, is there a simpler way to do this, produce the count of 'A' and 'B' respectively, without something like 'data': np.ones(3,) ?



It doesn't have to be a pandas method, numpy or python native function are also appreciated.










share|improve this question



















  • 3





    df.key.value_counts()?

    – coldspeed
    Mar 7 at 0:23














0












0








0








I am grouping and counting a set of data.



df = pd.DataFrame('key': ['A', 'B', 'A'],
'data': np.ones(3,))
df.groupby('key').count()


outputs



 data
key
A 2
B 1


The piece of code above works though, I wonder if there is a simpler one.



'data': np.ones(3,) seems to be a placeholder and indispensable.



pd.DataFrame(['A', 'B', 'A']).groupby(0).count()


outputs



A
B


My question is, is there a simpler way to do this, produce the count of 'A' and 'B' respectively, without something like 'data': np.ones(3,) ?



It doesn't have to be a pandas method, numpy or python native function are also appreciated.










share|improve this question
















I am grouping and counting a set of data.



df = pd.DataFrame('key': ['A', 'B', 'A'],
'data': np.ones(3,))
df.groupby('key').count()


outputs



 data
key
A 2
B 1


The piece of code above works though, I wonder if there is a simpler one.



'data': np.ones(3,) seems to be a placeholder and indispensable.



pd.DataFrame(['A', 'B', 'A']).groupby(0).count()


outputs



A
B


My question is, is there a simpler way to do this, produce the count of 'A' and 'B' respectively, without something like 'data': np.ones(3,) ?



It doesn't have to be a pandas method, numpy or python native function are also appreciated.







python pandas numpy






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 7 at 2:07









Ced

456418




456418










asked Mar 7 at 0:22









shiqangpanshiqangpan

123




123







  • 3





    df.key.value_counts()?

    – coldspeed
    Mar 7 at 0:23













  • 3





    df.key.value_counts()?

    – coldspeed
    Mar 7 at 0:23








3




3





df.key.value_counts()?

– coldspeed
Mar 7 at 0:23






df.key.value_counts()?

– coldspeed
Mar 7 at 0:23













3 Answers
3






active

oldest

votes


















0














Use a Series instead.



>>> import pandas as pd
>>>
>>> data = ['A', 'A', 'A', 'B', 'C', 'C', 'D', 'D', 'D', 'D', 'D']
>>>
>>> pd.Series(data).value_counts()
D 5
A 3
C 2
B 1
dtype: int64





share|improve this answer






























    0














    Use a defaultdict:



    from collections import defaultdict

    data = ['A', 'A', 'B', 'A', 'C', 'C', 'A']

    d = defaultdict(int)

    for element in data:
    d[element] += 1

    d # output: defaultdict(int, 'A': 4, 'B': 1, 'C': 2)





    share|improve this answer






























      0














      There's not any grouping , just counting, so you can use



      from collections import Counter
      counter(['A', 'B', 'A'])





      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%2f55034235%2fis-there-a-simpler-way-to-group-and-count-with-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









        0














        Use a Series instead.



        >>> import pandas as pd
        >>>
        >>> data = ['A', 'A', 'A', 'B', 'C', 'C', 'D', 'D', 'D', 'D', 'D']
        >>>
        >>> pd.Series(data).value_counts()
        D 5
        A 3
        C 2
        B 1
        dtype: int64





        share|improve this answer



























          0














          Use a Series instead.



          >>> import pandas as pd
          >>>
          >>> data = ['A', 'A', 'A', 'B', 'C', 'C', 'D', 'D', 'D', 'D', 'D']
          >>>
          >>> pd.Series(data).value_counts()
          D 5
          A 3
          C 2
          B 1
          dtype: int64





          share|improve this answer

























            0












            0








            0







            Use a Series instead.



            >>> import pandas as pd
            >>>
            >>> data = ['A', 'A', 'A', 'B', 'C', 'C', 'D', 'D', 'D', 'D', 'D']
            >>>
            >>> pd.Series(data).value_counts()
            D 5
            A 3
            C 2
            B 1
            dtype: int64





            share|improve this answer













            Use a Series instead.



            >>> import pandas as pd
            >>>
            >>> data = ['A', 'A', 'A', 'B', 'C', 'C', 'D', 'D', 'D', 'D', 'D']
            >>>
            >>> pd.Series(data).value_counts()
            D 5
            A 3
            C 2
            B 1
            dtype: int64






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Mar 7 at 0:56









            Marcus LimMarcus Lim

            1,405110




            1,405110























                0














                Use a defaultdict:



                from collections import defaultdict

                data = ['A', 'A', 'B', 'A', 'C', 'C', 'A']

                d = defaultdict(int)

                for element in data:
                d[element] += 1

                d # output: defaultdict(int, 'A': 4, 'B': 1, 'C': 2)





                share|improve this answer



























                  0














                  Use a defaultdict:



                  from collections import defaultdict

                  data = ['A', 'A', 'B', 'A', 'C', 'C', 'A']

                  d = defaultdict(int)

                  for element in data:
                  d[element] += 1

                  d # output: defaultdict(int, 'A': 4, 'B': 1, 'C': 2)





                  share|improve this answer

























                    0












                    0








                    0







                    Use a defaultdict:



                    from collections import defaultdict

                    data = ['A', 'A', 'B', 'A', 'C', 'C', 'A']

                    d = defaultdict(int)

                    for element in data:
                    d[element] += 1

                    d # output: defaultdict(int, 'A': 4, 'B': 1, 'C': 2)





                    share|improve this answer













                    Use a defaultdict:



                    from collections import defaultdict

                    data = ['A', 'A', 'B', 'A', 'C', 'C', 'A']

                    d = defaultdict(int)

                    for element in data:
                    d[element] += 1

                    d # output: defaultdict(int, 'A': 4, 'B': 1, 'C': 2)






                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Mar 7 at 1:43









                    jfaccionijfaccioni

                    3916




                    3916





















                        0














                        There's not any grouping , just counting, so you can use



                        from collections import Counter
                        counter(['A', 'B', 'A'])





                        share|improve this answer



























                          0














                          There's not any grouping , just counting, so you can use



                          from collections import Counter
                          counter(['A', 'B', 'A'])





                          share|improve this answer

























                            0












                            0








                            0







                            There's not any grouping , just counting, so you can use



                            from collections import Counter
                            counter(['A', 'B', 'A'])





                            share|improve this answer













                            There's not any grouping , just counting, so you can use



                            from collections import Counter
                            counter(['A', 'B', 'A'])






                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Mar 7 at 3:14









                            user2699user2699

                            1,379718




                            1,379718



























                                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%2f55034235%2fis-there-a-simpler-way-to-group-and-count-with-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

                                1928 у кіно

                                Захаров Федір Захарович

                                Ель Греко