R dcast相当于python pandas

时间:2021-08-31 16:18:18

I am trying to do the equivalent of the below commands in python:

我试图在python中执行相当于下面的命令:

test <- data.frame(convert_me=c('Convert1','Convert2','Convert3'),
                   values=rnorm(3,45, 12), age_col=c('23','33','44'))
test

library(reshape2)
t <- dcast(test, values ~ convert_me+age_col, length  )
t

That is, this:

就是这样:

convert_me   values     age_col
Convert1     21.71502      23
Convert2     58.35506      33
Convert3     60.41639      44

becomes this:

values     Convert2_33 Convert1_23 Convert3_44
21.71502          0           1           0
58.35506          1           0           0
60.41639          0           0           1

I know that with dummy variables I can get the value of the columns and transform as the name of the column, but is there a way to merge them(combination) easily, as R does?

我知道使用虚拟变量我可以得到列的值并转换为列的名称,但有没有办法轻松地合并它们(组合),就像R一样?

2 个解决方案

#1


7  

You can use the crosstab function for this:

您可以使用交叉表功能:

In [14]: pd.crosstab(index=df['values'], columns=[df['convert_me'], df['age_col']])
Out[14]: 
convert_me  Convert1  Convert2  Convert3
age_col           23        33        44
values                                  
21.71502           1         0         0
58.35506           0         1         0
60.41639           0         0         1

or the pivot_table (with len as the aggregating function, but here you have to fillna the NaNs with zeros manually):

或者pivot_table(使用len作为聚合函数,但是你必须手动用零填充NaN):

In [18]: df.pivot_table(index=['values'], columns=['age_col', 'convert_me'], aggfunc=len).fillna(0)
Out[18]: 
age_col           23        33        44
convert_me  Convert1  Convert2  Convert3
values                                  
21.71502           1         0         0
58.35506           0         1         0
60.41639           0         0         1

See here for the docs on this: http://pandas.pydata.org/pandas-docs/stable/reshaping.html#pivot-tables-and-cross-tabulations

请参阅此处了解相关文档:http://pandas.pydata.org/pandas-docs/stable/reshaping.html#pivot-tables-and-cross-tabulations

Most functions in pandas will return a multi-level (hierarchical) index, in this case for the columns. If you want to 'melt' this into one level like in R you can do:

pandas中的大多数函数将返回多级(分层)索引,在本例中为列。如果你想把它“融化”成一个像R一样的水平,你可以做到:

In [15]: df_cross = pd.crosstab(index=df['values'], columns=[df['convert_me'], df['age_col']])

In [16]: df_cross.columns = ["{0}_{1}".format(l1, l2) for l1, l2 in df_cross.columns]

In [17]: df_cross
Out[17]: 
          Convert1_23  Convert2_33  Convert3_44
values                                         
21.71502            1            0            0
58.35506            0            1            0
60.41639            0            0            1

#2


1  

We can use pd.get_dummies function. In the current pandas 0.22.0, it is common to use pd.get_dummies when one-hot encoding to Dataframe.

我们可以使用pd.get_dummies函数。在当前的pandas 0.22.0中,当对Dataframe进行单热编码时,通常使用pd.get_dummies。

import pandas as pd

df_dummies = pd.get_dummies(
    df[['convert_me', 'age_col']].apply(lambda x: '_'.join(x.astype(str)), axis=1),
    prefix_sep='')
df = pd.concat([df["values"], df_dummies], axis=1)
# Out[39]:
#      values  Convert1_23  Convert2_33  Convert3_44
# 0  21.71502            1            0            0
# 1  58.35506            0            1            0
# 2  60.41639            0            0            1

#1


7  

You can use the crosstab function for this:

您可以使用交叉表功能:

In [14]: pd.crosstab(index=df['values'], columns=[df['convert_me'], df['age_col']])
Out[14]: 
convert_me  Convert1  Convert2  Convert3
age_col           23        33        44
values                                  
21.71502           1         0         0
58.35506           0         1         0
60.41639           0         0         1

or the pivot_table (with len as the aggregating function, but here you have to fillna the NaNs with zeros manually):

或者pivot_table(使用len作为聚合函数,但是你必须手动用零填充NaN):

In [18]: df.pivot_table(index=['values'], columns=['age_col', 'convert_me'], aggfunc=len).fillna(0)
Out[18]: 
age_col           23        33        44
convert_me  Convert1  Convert2  Convert3
values                                  
21.71502           1         0         0
58.35506           0         1         0
60.41639           0         0         1

See here for the docs on this: http://pandas.pydata.org/pandas-docs/stable/reshaping.html#pivot-tables-and-cross-tabulations

请参阅此处了解相关文档:http://pandas.pydata.org/pandas-docs/stable/reshaping.html#pivot-tables-and-cross-tabulations

Most functions in pandas will return a multi-level (hierarchical) index, in this case for the columns. If you want to 'melt' this into one level like in R you can do:

pandas中的大多数函数将返回多级(分层)索引,在本例中为列。如果你想把它“融化”成一个像R一样的水平,你可以做到:

In [15]: df_cross = pd.crosstab(index=df['values'], columns=[df['convert_me'], df['age_col']])

In [16]: df_cross.columns = ["{0}_{1}".format(l1, l2) for l1, l2 in df_cross.columns]

In [17]: df_cross
Out[17]: 
          Convert1_23  Convert2_33  Convert3_44
values                                         
21.71502            1            0            0
58.35506            0            1            0
60.41639            0            0            1

#2


1  

We can use pd.get_dummies function. In the current pandas 0.22.0, it is common to use pd.get_dummies when one-hot encoding to Dataframe.

我们可以使用pd.get_dummies函数。在当前的pandas 0.22.0中,当对Dataframe进行单热编码时,通常使用pd.get_dummies。

import pandas as pd

df_dummies = pd.get_dummies(
    df[['convert_me', 'age_col']].apply(lambda x: '_'.join(x.astype(str)), axis=1),
    prefix_sep='')
df = pd.concat([df["values"], df_dummies], axis=1)
# Out[39]:
#      values  Convert1_23  Convert2_33  Convert3_44
# 0  21.71502            1            0            0
# 1  58.35506            0            1            0
# 2  60.41639            0            0            1