如標題所述,我想對 中的分類變量進行一些總結分析pandas,但搜索了一段時間沒有找到令人滿意的解決方案。因此,我開發了以下代碼作為一種自我回答問題,希望有人可以幫助改進。test_df = pd.DataFrame({'x':['a', 'b','b','c'], 'y':[1, 0, 0, np.nan], 'z':['Jay', 'Jade', 'Jia', ''], 'u':[1, 2, 3, 3]})def cat_var_describe(input_df, var_list): df = input_df.copy() # dataframe to store result res = pd.DataFrame({'var_name', 'values', 'count'}) for var in var_list: temp_res = df[var].value_counts(dropna=False).rename_axis('unique_values').reset_index(name='counts') temp_res['var_name'] = var if var==var_list[0]: res = temp_res.copy() else: res = pd.concat([res, temp_res], axis=0) res = res[['var_name', 'unique_values', 'counts']] return rescat_des_test = cat_var_describe(test_df, ['x','y','z','u'])cat_des_test任何有用的建議將不勝感激。
3 回答

Smart貓小萌
TA貢獻1911條經驗 獲得超7個贊
您可以使用 pandas DataFramedescribe()
方法。 describe()
默認情況下僅包含數字數據。要包含分類變量,您必須使用include
參數。
using'object'
僅返回非數字數據
test_df.describe(include='object')
using返回統計信息不適合數據類型的'all'
所有列的摘要NaN
test_df.describe(include='all')
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.describe.html

郎朗坤
TA貢獻1921條經驗 獲得超9個贊
您可以使用該unique()
方法獲取列的各個值的列表,例如:
test_df['x'].unique()
要獲取列中值出現的次數,您可以使用value_counts()
:
test_df['x'].value_counts()
所有列的簡化循環DataFrame
可能如下所示:
for col in list(test_df): print('variable:', col) print(test_df[col].value_counts(dropna=False).to_string())

一只斗牛犬
TA貢獻1784條經驗 獲得超2個贊
您可以使用描述函數
test_df.describe()
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.describe.html
添加回答
舉報
0/150
提交
取消