【问题标题】:dplyr n() equivalent in Pandas?Pandas 中的 dplyr n() 等价物?
【发布时间】:2022-06-21 00:47:12
【问题描述】:

rdplyr我可以像这样创建一个列索引:

df %>% mutate(id = 1:n())

如何在 Pandas 中做到这一点?我试过这些:

df['id'] = 1:len(df)

df['id'] = 1:df.iloc[-1]

r 方法特别好,因为它适用于分组,所以 n() 将计算 group_by 分组的长度...

【问题讨论】:

  • 范围? np.arange?请与预期输出共享示例数据框
  • Cumcount 也可能适用于此。

标签: python r pandas dplyr


【解决方案1】:

这取决于你想做什么。

假设这个输入:

# R
df = data.frame(A=c(1,1,2,2,2));
# python
df = pd.DataFrame({'A': [1,1,2,2,2]})

要有一个全局计数器:

# R
df %>% mutate(id = 1:n());
# python
df['id'] = np.arange(len(df))+1
# or
df.assign(id=np.arange(len(df))+1)

每组有一个计数器:

# R
df %>% group_by(A) %>% mutate(id2 = 1:n());
# python
df['id2'] = df.groupby('A').cumcount().add(1)
# or
df.assign(id2=df.groupby('A').cumcount().add(1))

输出:

   A  id  id2
0  1   1    1
1  1   2    2
2  2   3    1
3  2   4    2
4  2   5    3

【讨论】:

  • 谢谢!请问+1.add(1)是怎么回事?
  • @stevezissou 在 python 计数中从 0 开始,这只是为了匹配 R 方式。您可以将其删除以从 0 开始计数;)
  • 知道了,感谢您的帮助!
【解决方案2】:

datar:

>>> from datar.all import mutate, n, seq
>>> from datar.datasets import table1
>>> 
>>> table1 >> mutate(id = seq(n()))
       country    year   cases  population      id
      <object> <int64> <int64>     <int64> <int64>
0  Afghanistan    1999     745    19987071       1
1  Afghanistan    2000    2666    20595360       2
2       Brazil    1999   37737   172006362       3
3       Brazil    2000   80488   174504898       4
4        China    1999  212258  1272915272       5
5        China    2000  213766  1280428583       6

【讨论】:

    猜你喜欢
    • 2019-12-12
    • 2017-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-15
    • 2020-07-21
    • 2020-04-09
    • 2019-12-14
    相关资源
    最近更新 更多