Python 如何获得与R中类似的Pandas数据帧摘要?

Python 如何获得与R中类似的Pandas数据帧摘要?,python,r,pandas,dataframe,Python,R,Pandas,Dataframe,不同的规模允许不同类型的操作。我想指定数据帧df中列的比例。然后,df.descripe()应该考虑到这一点 例子 标称刻度:标称刻度仅允许检查等效性。例如性别、姓名、城市名称。您基本上只能计算它们出现的频率,并给出最常见的(模式) 顺序刻度:您可以排序,但不能说出一个与另一个的距离。布料尺寸就是一个例子。可以计算此比例的中值/最小值/最大值 定量量表:您可以计算这些量表的平均值、标准偏差和分位数 代码示例 给予 这是不好的,因为vs是一个二进制变量,用于指示汽车是采用v型发动机还是直置发动

不同的规模允许不同类型的操作。我想指定数据帧
df
中列的比例。然后,
df.descripe()
应该考虑到这一点

例子
  • 标称刻度:标称刻度仅允许检查等效性。例如性别、姓名、城市名称。您基本上只能计算它们出现的频率,并给出最常见的(模式)
  • 顺序刻度:您可以排序,但不能说出一个与另一个的距离。布料尺寸就是一个例子。可以计算此比例的中值/最小值/最大值
  • 定量量表:您可以计算这些量表的平均值、标准偏差和分位数
代码示例 给予

这是不好的,因为
vs
是一个二进制变量,用于指示汽车是采用v型发动机还是直置发动机()。因此,该特征具有名义规模。因此,最小值/最大值/标准值/平均值不适用。应该计算0和1出现的频率

在R中,可以执行以下操作:

mtcars$vs = factor(mtcars$vs, levels=c(0, 1), labels=c("straight engine", "V-Engine"))
mtcars$am = factor(mtcars$am, levels=c(0, 1), labels=c("Automatic", "Manual"))
mtcars$gear = factor(mtcars$gear)
mtcars$carb = factor(mtcars$carb)
summary(mtcars)
            counts    freqs
categories                 
3               15  0.46875
4               12  0.37500
5                5  0.15625
得到

      mpg             cyl             disp             hp             drat      
 Min.   :10.40   Min.   :4.000   Min.   : 71.1   Min.   : 52.0   Min.   :2.760  
 1st Qu.:15.43   1st Qu.:4.000   1st Qu.:120.8   1st Qu.: 96.5   1st Qu.:3.080  
 Median :19.20   Median :6.000   Median :196.3   Median :123.0   Median :3.695  
 Mean   :20.09   Mean   :6.188   Mean   :230.7   Mean   :146.7   Mean   :3.597  
 3rd Qu.:22.80   3rd Qu.:8.000   3rd Qu.:326.0   3rd Qu.:180.0   3rd Qu.:3.920  
 Max.   :33.90   Max.   :8.000   Max.   :472.0   Max.   :335.0   Max.   :4.930  
       wt             qsec                     vs             am     gear   carb  
 Min.   :1.513   Min.   :14.50   straight engine:18   Automatic:19   3:15   1: 7  
 1st Qu.:2.581   1st Qu.:16.89   V-Engine       :14   Manual   :13   4:12   2:10  
 Median :3.325   Median :17.71                                       5: 5   3: 3  
 Mean   :3.217   Mean   :17.85                                              4:10  
 3rd Qu.:3.610   3rd Qu.:18.90                                              6: 1  
 Max.   :5.424   Max.   :22.90                                              8: 1  
熊猫也可能有类似的情况吗

我试过了

df["vs"] = df["vs"].astype('category')

但是这会使“vs”从描述中消失。

派对迟到了,但最近我碰巧也遇到了一些同样的问题,所以我想我会分享一下我对这一挑战的看法


在我看来,R更擅长处理分类变量。但是,有几种方法可以通过使用Python与
pd.category()
pd.GetDummies()
descripe()
来模拟这些功能

这个特定数据集中的挑战是分类变量具有非常不同的属性。例如,对于自动档位或手动档位,
am分别为0或1。而
档位为3、4或5
,但仍被合理地视为分类值而非数值。因此,对于
am
我将用“自动”和“分类”替换0和1,但对于齿轮,我将应用
pd.GetDummies()
为每个齿轮类别获得0或1,以便能够轻松计算出有多少个模型,例如,3个齿轮

我有一个实用函数已经存在了一段时间,昨天我改进了一点。它当然不是最基本的元素,但它应该提供与使用R代码片段相同的信息。最终输出表由行数不等的列组成。我没有将一个类似的表作为数据帧并用NaN填充它,而是将信息分为两部分:一个表用于数值,另一个表用于分类值,因此最终得到以下结果:

                 count
Straight Engine     18
V engine            14
automatic           13
manual              19
cyl_4               11
cyl_6                7
cyl_8               14
gear_3              15
gear_4              12
gear_5               5
carb_1               7
carb_2              10
carb_3               3
carb_4              10
carb_6               1
carb_8               1
             mpg        disp          hp       drat         wt       qsec
count  32.000000   32.000000   32.000000  32.000000  32.000000  32.000000
mean   20.090625  230.721875  146.687500   3.596563   3.217250  17.848750
std     6.026948  123.938694   68.562868   0.534679   0.978457   1.786943
min    10.400000   71.100000   52.000000   2.760000   1.513000  14.500000
25%    15.425000  120.825000   96.500000   3.080000   2.581250  16.892500
50%    19.200000  196.300000  123.000000   3.695000   3.325000  17.710000
75%    22.800000  326.000000  180.000000   3.920000   3.610000  18.900000
max    33.900000  472.000000  335.000000   4.930000   5.424000  22.900000
以下是简单复制和粘贴的整个过程:

# imports
import pandas as pd

# to easily access R datasets:
# pip install pydataset
from pydataset import data 

# Load dataset
df_mtcars = data('mtcars')


# The following variables: cat, dum, num and recoding
# are used in the function describeCat/df, dummies, recode, categorical) below

# Specify which variables are dummy variables [0 or 1], 
# ategorical [multiple categories] or numeric
cat = ['cyl', 'gear', 'carb']
dum = ['vs', 'am']
num = [c for c in list(df_mtcars) if c not in cat+dum]

# Also, define a dictionary that describes how some dummy variables should be recoded
# For example, in the series am, 0 is recoded as automatic and 1 as manual gears
recoding = {'am':['manual', 'automatic'], 'vs':['Straight Engine', 'V engine']}

# The function:
def describeCat(df, dummies, recode, categorical):
    """ Retrieves specified dummy and categorical variables
        from a pandas DataFrame and describes them (just count for now).

        Dummy variables [0 or 1] can be recoded to categorical variables
        by specifying a dictionary

    Keyword arguments:
    df -- pandas DataFrame
    dummies -- list of column names to specify dummy variables [0 or 1]
    recode -- dictionary to specify which and how dummyvariables should be recoded
    categorical -- list of columns names to specify catgorical variables

    """


    # Recode dummy variables
    recoded = []

    # DataFrame to store recoded variables
    df_recoded = pd.DataFrame()

    for dummy in dummies:
        if dummy in recode.keys():

            dummySeries = df[dummy].copy(deep = True).to_frame()
            dummySeries[dummy][dummySeries[dummy] == 0] = recode[dummy][0]
            dummySeries[dummy][dummySeries[dummy] == 1] = recode[dummy][1]
            recoded.append(pd.Categorical(dummySeries[dummy]).describe())  

            df_rec = pd.DataFrame(pd.Categorical(dummySeries[dummy]).describe())
            df_recoded = pd.concat([df_recoded.reset_index(),df_rec.reset_index()],
                                    ignore_index=True).set_index('categories')

    df_recoded = df_recoded['counts'].to_frame()

    # Rename columns and change datatype
    df_recoded['counts'] = df_recoded['counts'].astype(int)
    df_recoded.columns = ['count']


    # Since categorical variables will be transformed into dummy variables,
    # all remaining dummy variables (after recoding) can be treated the
    # same way as the categorical variables
    unrecoded = [var for var in dum if var not in recoding.keys()]
    categorical = categorical + unrecoded

    # Categorical split into dummy variables will have the same index
    # as the original dataframe
    allCats = pd.DataFrame(index = df.index)

    # apply pd.get_dummies on all categoirical variables
    for cat in categorical:
        newCats = pd.DataFrame(data = pd.get_dummies(pd.Categorical(df_mtcars[cat]), prefix = cat))
        newCats.index = df_mtcars.index
        allCats = pd.concat([allCats, newCats], axis = 1)
        df_cat = allCats.sum().to_frame()
    df_cat.columns = ['count']

    # gather output dataframes
    df_output = pd.concat([df_recoded, df_cat], axis = 0)


    return(df_output)

# Test run: Build a dataframe that describes the dummy and categorical variables
df_categorical = describeCat(df = df_mtcars, dummies = dum, recode = recoding, categorical = cat)

# describe numerical variables
df_numerical = df_mtcars[num].describe()

print(df_categorical)
print(df_numerical)

关于分类变量和descripe()的旁注:

我在上面的函数中使用
pd.category()
的原因是
descripe()
的输出似乎有点不稳定。有时
df_mtcars['gear'].astype('category').descripe()
返回:

count    32.000000
mean      3.687500
std       0.737804
min       3.000000
25%       3.000000
50%       4.000000
75%       4.000000
max       5.000000
Name: gear, dtype: float64
鉴于它被视为一个分类变量,它应该返回:

count     32
unique     3
top        3
freq      15
Name: gear, dtype: int64
我在这里可能是错的,我在复制这个问题上遇到了问题,但我可以发誓,这种情况时有发生

pd.category()
上使用
descripe()
,可以输出自己的格式,但至少看起来是稳定的

            counts    freqs
categories                 
3               15  0.46875
4               12  0.37500
5                5  0.15625

和一些关于

以下是将该函数应用于df_mtcars['gear']
时发生的情况:

# code
pd.get_dummies(df_mtcars['gear'].astype('category'), prefix = 'gear')

# output
                     gear_3  gear_4  gear_5
Mazda RX4                 0       1       0
Mazda RX4 Wag             0       1       0
Datsun 710                0       1       0
Hornet 4 Drive            1       0       0
Hornet Sportabout         1       0       0
Valiant                   1       0       0
.
.
.
Ferrari Dino              0       0       1
Maserati Bora             0       0       1
Volvo 142E                0       1       0
但在本例中,我只需使用
value\u counts()
,即可获得以下结果:

mtcars$vs = factor(mtcars$vs, levels=c(0, 1), labels=c("straight engine", "V-Engine"))
mtcars$am = factor(mtcars$am, levels=c(0, 1), labels=c("Automatic", "Manual"))
mtcars$gear = factor(mtcars$gear)
mtcars$carb = factor(mtcars$carb)
summary(mtcars)
            counts    freqs
categories                 
3               15  0.46875
4               12  0.37500
5                5  0.15625

这也恰好类似于对
pd.category()
变量使用
descripe()
时的输出。

我遇到了同样的问题
df.descripe()
适用于数值

为了对类别中的值进行计数,我编写了以下代码:

for category in df.columns:
     print('\n',category)
     for typ in df.groupby(category).groups:
          print(typ,'\t',len(df.groupby(category).groups[typ]))

我希望它会有所帮助:)

您可以通过指定
df.descripe(include='all')
@NickilMaveli Hm来为所有列使用
descripe
。好的,这会使
df[“vs”]
再次出现,但输出的信息量远小于R。您看过了吗@Martin Thoma我的建议对你有何帮助?@Martin Thoma我的建议有助于解决你的问题吗?如果没有,请告诉我,我会再看一遍。还是你自己找到了更好的方法?