'Converting column values to rows [duplicate]
I have a dataset where all values in column B
are the same. It looks like this:
A B
0 Marble Hill Pizza Place
1 Chinatown Pizza Place
2 Washington Pizza Place
3 Washington Pizza Place
4 Inwood Pizza Place
5 Inwood Pizza Place
I wish to convert column A
values to rows. Then column B
should count the number occurrences of each value from A
.
I want it to look like this:
B
Marble Hill 1
Chinatown 1
Washington 2
Inwood 2
Solution 1:[1]
pandas's value_counts() does exactly that. It returns a series with the number of occurrences of each value.
new_df = df["A"].value_counts()
Solution 2:[2]
Based on the way you are describing your data, it looks like you have a Pandas dataframe.
If that is the case then you can use the value_counts
method on column A
to get the result you want.
Assuming your dataframe is stored in the variable name df
, then...
df['A'].value_counts()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Roim |
Solution 2 | SherylHohman |