我想提取数据框中几列的模式并将它们存储在列表中。
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
我希望列表中的模式值如下所示:
['White','High School','Female','Single','Rental',1]
相反,它们看起来像这样:
[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]
如何抑制 dtype 值和 0?
答案 0 :(得分:2)
做:
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)
输出
['White', 'High School', 'Female', 'Single', 'Rental', 1]