NWWPA
NWWPA

Reputation: 59

remove dtype info from pandas mode values

I want to extract the mode for several columns in a dataframe and store them in a list.

mode_list = ['Race','Education','Gender','Married','Housing','HH size']
mode_values =[]

counter = 0
while counter < len(mode_list):
    mode_value = df[str(mode_list[counter])].mode()
    mode_values.append(mode_value)
    counter = counter + 1

I want the mode values in the list to look like this:

['White','High School','Female','Single','Rental',1]

Instead they look like this:

[0    White
dtype: object, 0    High School
dtype: object, 0    Female
dtype: object, 0    Single
dtype: object, 0    Rental
dtype: object, 0    1.0
dtype: float64]

How can I suppress the dtype value and the 0?

Upvotes: 1

Views: 636

Answers (1)

Dani Mesejo
Dani Mesejo

Reputation: 61910

Do:

import pandas as pd

# dummy setup
mode_list = ['Race', 'Education', 'Gender', 'Married', 'Housing', 'HH size']
df = pd.DataFrame(data=[['White', 'High School', 'Female', 'Single', 'Rental', 1]], columns=mode_list)

# extract mode
mode_values = df[mode_list].mode().values[0].tolist()
print(mode_values)

Output

['White', 'High School', 'Female', 'Single', 'Rental', 1]

Upvotes: 2

Related Questions