抱歉,如果之前有人问过类似的问题,我到处找了找,但找不到解决方案。
我的数据集如下所示
data1 = {'Group':['Winner','Winner','Winner','Winner','Loser','Loser'],
'Study': ['Read','Read','Notes','Cheat','Read','Read'],
'Score': [1,.90,.80,.70,1,.90]}
df1 = pd.DataFrame(data=data1)
此数据帧跨越数十行,并具有一组数值列和一组字符串列。我想将其压缩为1行,其中每个条目只是该列的平均值或模式。如果该列是数字,则取平均值,否则,采用模式。在我的实际用例中,数字列和对象列的顺序是随机的,所以我希望使用一个迭代循环来检查每一列要采取的操作。
我试过了,但它不起作用,它似乎是以整个系列为模式。
for i in df1:
if df1[i].dtype == 'float64':
df1[i] = df1[i].mean()
感谢您的帮助,谢谢!
发布于 2021-03-23 22:11:27
您可以将describe
与'all'
一起使用,后者根据dtype
计算统计信息。它确定object的top
(模式)和数字列的mean
。然后再合并。
s = df1.describe(include='all')
s = s.loc['top'].combine_first(s.loc['mean'])
#Group Winner
#Study Read
#Score 0.883333
#Name: top, dtype: object
发布于 2021-03-23 22:07:28
np.number
和select_dtypes
s = df1.select_dtypes(np.number).mean()
df1.drop(s.index, axis=1).mode().iloc[0].append(s)
Group Winner
Study Read
Score 0.883333
dtype: object
变体
g = df1.dtypes.map(lambda x: np.issubdtype(x, np.number))
d = {k: d for k, d in df1.groupby(g, axis=1)}
pd.concat([d[False].mode().iloc[0], d[True].mean()])
Group Winner
Study Read
Score 0.883333
dtype: object
发布于 2021-03-23 22:07:02
以下是您的解决方案的一个细微变化,可以完成这项工作
res = {}
for col_name, col_type in zip(df1.columns, df1.dtypes):
if pd.api.types.is_numeric_dtype(col_type):
res[col_name] = df1[col_name].mean()
else:
res[col_name]= df1[col_name].mode()[0]
pd.DataFrame(res, index = [0])
返回
Group Study Score
0 Winner Read 0.883333
一个系列中可能有多个mode
--此解决方案选择第一个
https://stackoverflow.com/questions/66771882
复制