Pandas有没有类似于tidyr中的uncount函数的等效函数?

4
假设我们有一个包含变量和它们频率分组的表格:
在R中:
> df

# A tibble: 3 x 3
  Cough Fever cases
  <lgl> <lgl> <dbl>
1 TRUE  FALSE     1
2 FALSE FALSE     2
3 TRUE  TRUE      3

然后我们可以使用 tidyr::uncount 函数来得到一个包含各个实例的数据框:

> uncount(df, cases)

# A tibble: 6 x 2
  Cough Fever
  <lgl> <lgl>
1 TRUE  FALSE
2 FALSE FALSE
3 FALSE FALSE
4 TRUE  TRUE 
5 TRUE  TRUE 
6 TRUE  TRUE 

Python/Pandas中有相应的等价物吗?

4个回答

3
除了其他解决方案外,您还可以结合使用takerepeatdrop
import pandas as pd
df = pd.DataFrame({'Cough': [True, False, True],
                   'Fever': [False, False, True],
                   'cases': [1, 2, 3]})

df.take(df.index.repeat(df.cases)).drop(columns="cases")


    Cough   Fever
0   True    False
1   False   False
1   False   False
2   True    True
2   True    True
2   True    True

在索引位置之前,您还可以预先选择要索引的列:

df.loc(axis=1)[:'Fever'].take(df.index.repeat(df.cases))
   Cough  Fever
0   True  False
1  False  False
1  False  False
2   True   True
2   True   True
2   True   True

1
你有一个行索引,并根据计数重复它,例如在R中,你可以这样做:
df[rep(1:nrow(df),df$cases),]

首先获取类似您的数据:

df = pd.DataFrame({'x':[1,1,2,2,2,2],'y':[0,1,0,1,1,1]})
counts = df.groupby(['x','y']).size().reset_index()
counts.columns = ['x','y','n']

    x   y   n
0   1   0   1
1   1   1   1
2   2   0   1
3   2   1   3

然后:

counts.iloc[np.repeat(np.arange(len(counts)),counts.n),:2]

    x   y
0   1   0
1   1   1
2   2   0
3   2   1
3   2   1
3   2   1

1
我在Python中没有找到等效的函数,但这个方法可行。
df2 = df.pop('cases')
df = pd.DataFrame(df.values.repeat(df2, axis=0), columns=df.columns)

df['cases']被传递到df2,然后您创建一个新的DataFrame,其中原始DataFrame中的元素根据df2中的计数重复。如果有帮助,请告诉我。


0
与{{link1:datar}}一起使用tidyr的API一样容易:

>>> from datar.all import f, tribble, uncount
>>> df = tribble(
...     f.Cough, f.Fever, f.cases,
...     True,    False,   1,
...     False,   False,   2,
...     True,    True,    3
... )
>>> uncount(df, f.cases)
   Cough  Fever
  <bool> <bool>
0   True  False
1  False  False
2  False  False
3   True   True
4   True   True
5   True   True

我是这个软件包的作者。如果您有任何问题,请随时提交问题。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接