Python 如果为else,请按列中的数据类型键入 格式化熊猫的输出
我正在尝试以一种我可以在文字处理器中使用的最小混乱的格式自动从pandas获取输出。我使用描述性统计作为实践案例,因此我尝试使用Python 如果为else,请按列中的数据类型键入 格式化熊猫的输出,python,pandas,Python,Pandas,我正在尝试以一种我可以在文字处理器中使用的最小混乱的格式自动从pandas获取输出。我使用描述性统计作为实践案例,因此我尝试使用df[variable].descripe()的输出。我的问题是.descripe()根据列的dtype做出不同的响应(如果我正确理解的话) 对于数值列descripe()产生以下输出: count 306.000000 mean 36.823529 std 6.308587 min 10.000000 25% 33
df[variable].descripe()的输出。我的问题是.descripe()
根据列的dtype
做出不同的响应(如果我正确理解的话)
对于数值列descripe()
产生以下输出:
count 306.000000
mean 36.823529
std 6.308587
min 10.000000
25% 33.000000
50% 37.000000
75% 41.000000
max 50.000000
Name: gses_tot, dtype: float64
但是,对于分类列,它会生成:
count 306
unique 3
top Female
freq 166
Name: gender, dtype: object
由于这种差异,我需要不同的代码来捕获我需要的信息,然而,我似乎无法让我的代码处理分类变量
我试过的
我尝试了以下几种不同的版本:
for v in df.columns:
if df[v].dtype.name == 'category': #i've also tried 'object' here
c, u, t, f, = df[v].describe()
print(f'******{str(v)}******')
print(f'Largest category = {t}')
print(f'Percentage = {(f/c)*100}%')
else:
c, m, std, mi, tf, f, sf, ma, = df[v].describe()
print(f'******{str(v)}******')
print(f'M = {m}')
print(f'SD = {std}')
print(f'Range = {float(ma) - float(mi)}')
print(f'\n')
else
块中的代码工作正常,但是当我进入分类列时,我得到下面的错误
******age****** #this is the output I want to a numberical column
M = 34.21568627450981
SD = 11.983015946197659
Range = 53.0
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-24-f077cc105185> in <module>
6 print(f'Percentage = {(f/c)*100}')
7 else:
----> 8 c, m, std, mi, tf, f, sf, ma, = df[v].describe()
9 print(f'******{str(v)}******')
10 print(f'M = {m}')
ValueError: not enough values to unpack (expected 8, got 4)
您可以检查“描述”输出中包含哪些字段,并打印相应的部分:
import pandas as pd
df = pd.DataFrame({'categorical': pd.Categorical(['d','e','f']), 'numeric': [1, 2, 3], 'object': ['a', 'b', 'c']})
for v in df.columns:
desc = df[v].describe()
print(f'******{str(v)}******')
if 'top' in desc:
print(f'Largest category = {desc["top"]}')
print(f'Percentage = {(desc["freq"]/desc["count"])*100:.1f}%')
else:
print(f'M = {desc["mean"]}')
print(f'SD = {desc["std"]}')
print(f'Range = {float(desc["max"]) - float(desc["min"])}')
我建议从pandas开始,而不是编写自己的,这有助于抽象出许多困难的typerhaps如果是instance(df[v].dtype,pd.api.types.CategoricalDtype),请尝试
import pandas as pd
df = pd.DataFrame({'categorical': pd.Categorical(['d','e','f']), 'numeric': [1, 2, 3], 'object': ['a', 'b', 'c']})
for v in df.columns:
desc = df[v].describe()
print(f'******{str(v)}******')
if 'top' in desc:
print(f'Largest category = {desc["top"]}')
print(f'Percentage = {(desc["freq"]/desc["count"])*100:.1f}%')
else:
print(f'M = {desc["mean"]}')
print(f'SD = {desc["std"]}')
print(f'Range = {float(desc["max"]) - float(desc["min"])}')