【问题标题】:how to take the nth value from a column based on the value of another column (Python)如何根据另一列的值从一列中获取第 n 个值(Python)
【发布时间】:2021-09-22 22:11:19
【问题描述】:

这里有什么帮助吗?! 假设我有一个包含两列的数据框:

A | B

1 | b

1 | b

1 | a

2 | a

2 | b

3 | b

3 | c

3 | d

我想获取 colA 的每个值的第一次出现 会是这样的

A | B

1 | b

2 | a

3 | b

然后捕捉第二次出现 类似的东西:

A | B

1 | b

2 | b

3 | c

发生 3 次后

A | B

1 | a

2 | NULL

3 | d

关于如何做到这一点的任何提示??

【问题讨论】:

    标签: python python-3.x pandas list numpy


    【解决方案1】:

    IIUC,这是一种方法:

    df1 = df.pivot_table(index = 'A', columns = df.groupby('A').cumcount(), values = 'B', aggfunc = sum)
    result = [df1[col].reset_index(name='B')  for col in df1.columns] #this will give you the list of df's
    

    输出:

    [   A   B
     0  1   b
     1  2   a
     2  3   b,
        A   B
     0  1   b
     1  2   b
     2  3   c,
        A    B
     0  1    a
     1  2  NaN
     2  3    d]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-18
      • 1970-01-01
      • 1970-01-01
      • 2020-05-13
      • 2022-01-24
      相关资源
      最近更新 更多