Create a pandas data framework

I want to create a pandas framework with two columns, the first of which is the unique values ​​of one of my columns, and the second is the number of unique values.

I saw a lot of posts (such here ) that describe how to get the counts, but the problem I am facing is when I try to create a dataframe, the column values ​​become my index.

Example data: df = pd.DataFrame({'Color': ['Red', 'Red', 'Blue'], 'State': ['MA', 'PA', 'PA']}) . I want to end up with a dataframe like:

  Color Count 0 Red 2 1 Blue 1 

I tried the following, but in all cases the index ends with β€œColor” and the graph is the only column in the data frame.

Attempt 1:

 df2 = pd.DataFrame(data=df['Color'].value_counts()) # And resetting the index just gets rid of Color, which I want to keep df2 = df2.reset_index(drop=True) 

Attempt 2:

 df3 = df['Color'].value_counts() df3 = pd.DataFrame(data=df3, index=range(df3.shape[0])) 

Attempt 3:

 df4 = df.groupby('Color') df4 = pd.DataFrame(df4['Color'].count()) 
+7
source share
5 answers

Another way to do this using value_counts :

 In [10]: df = pd.DataFrame({'Color': ['Red', 'Red', 'Blue'], 'State': ['MA', 'PA', 'PA']}) In [11]: df.Color.value_counts().reset_index().rename(columns={'index': 'Color', 0: 'count'}) Out[11]: Color count 0 Red 2 1 Blue 1 
+9
source

Essentially equivalent to setting column names, but using the rename method instead:

 df.groupby('Color').count().reset_index().rename(columns={'State': 'Count'}) 
+2
source

One readable solution is to use to_frame and rename_axis :

 res = df['Color'].value_counts()\ .to_frame('count').rename_axis('Color')\ .reset_index() print(res) Color count 0 Red 2 1 Blue 1 
+1
source
 df=df.groupby('Color').count().reset_index() df.columns=['Color','Count'] 
-1
source
 label_sentiment=[] for i in range(len(score)): if score[i]==0: label_sentiment.append('NEUTRAL') elif score[i]>0: label_sentiment.append('POSITIVE') elif score[i]<0: label_sentiment.append('NEGATIVE') data['label_sentiment']=label_sentiment # #pythonT 
-2
source

All Articles