Pandas python.descripe()格式化/输出

2024-09-27 07:34:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图让.describe()函数以重新格式化的方式输出。 这是csv数据(testProp.csv

'name','prop'
A,1
A,2
B,  4
A,  3
B,  5
B,  2

当我输入以下内容时:

from pandas import *

data = read_csv('testProp.csv')

temp = data.groupby('name')['prop'].describe()
temp.to_csv('out.csv')

输出为:

name       
A     count    3.000000
      mean     2.000000
      std      1.000000
      min      1.000000
      25%      1.500000
      50%      2.000000
      75%      2.500000
      max      3.000000
B     count    3.000000
      mean     3.666667
      std      1.527525
      min      2.000000
      25%      3.000000
      50%      4.000000
      75%      4.500000
      max      5.000000
dtype: float64

但是,我需要以下格式的数据。我已经尝试过transpose(),并且希望继续使用describe(),并操纵它而不是a .agg([np.mean(), np.max(), etc.... )

    count   mean    std min 25% 50% 75% max
A   3   2   1   1   1.5 2   2.5 3
B    3  3.666666667 1.527525232 2   3   4   4.5 5

Tags: csv数据函数namedatacountnpmin
2条回答

在pandas v0.22中,可以使用unstack特性。在上面@Kumar answer的基础上,您可以使用pandas stack/unstack特性来处理它的变化。

from io import StringIO
import pandas as pd
df = pd.read_csv(StringIO("""name,prop
   A,1
   A,2
   B,  4
   A,  3
   B,  5
   B,  2"""))

df.shape
df
temp = df.groupby(['name'])['prop'].describe()
temp
temp.stack() #unstack(),unstack(level=-1) level can be -1, 0

查看文档pandas unstack了解更多详细信息

一种方法是首先执行^{},重置temp数据帧的索引,然后根据需要使用^{}。示例-

In [24]: df = pd.read_csv(io.StringIO("""name,prop
   ....: A,1
   ....: A,2
   ....: B,  4
   ....: A,  3
   ....: B,  5
   ....: B,  2"""))

In [25]: temp = df.groupby('name')['prop'].describe().reset_index()

In [26]: newdf = temp.pivot(index='name',columns='level_1',values=0)

In [27]: newdf.columns.name = ''   #This is needed so that the name of the columns is not `'level_1'` .

In [28]: newdf
Out[28]:
      25%  50%  75%  count  max      mean  min       std
name
A     1.5    2  2.5      3    3  2.000000    1  1.000000
B     3.0    4  4.5      3    5  3.666667    2  1.527525

然后您可以将这个newdf保存到csv。

相关问题 更多 >

    热门问题