【问题标题】:Shifted Series Join to Dataframe with Concat使用 Concat 将系列移位连接到数据框
【发布时间】:2021-03-14 21:44:37
【问题描述】:

有一个 DataFrame z 有

['title','module_number','beginners','finishers'] 

列。我需要转移z.beginners 系列,因为最后一个module_number 应该有NaN,并将其作为新列z.shift 加入DataFrame。

我尝试使用pd.concat 来实现。我的代码:

def exp2(df):
    
    fx = df.join(df.beginners[1:].rename('shifted').reset_index()).drop('index', axis =1)
    return fx

def exp3(z,lst):
    
    common = list()
    
    for title in lst:

        df = z[z['title'] == title]
        example = exp2(df)
        common.append(example)
        
    return pd.concat(common)

exp3(z, z.title.unique())

这仅适用于z 中的第一个标题,而不适用于第二个标题。但是,它不适用于任何其他标题:

        title module_number beginners finishers shift
    0   Uu    1             518       458       434
    1   Uu    2             434       406       NaN
    3   Kk    1             627       563       27
    4   Kk    2             521       427       NaN
    5   Rr    1             158       142       NaN
    6   Rr    2             136       106       NaN

有谁知道替代解决方案或我可以如何增强我的代码?

【问题讨论】:

    标签: python pandas series concat shift


    【解决方案1】:

    我刚刚做到了没有循环的方式:

    shifted = z.beginners.where(z.module_number != 1)[1:]
    z.join(shifted.rename('shifted').reset_index()).drop('index',axis = 1)
    

    【讨论】:

    • 也可以使用.shift(1) func
    猜你喜欢
    • 1970-01-01
    • 2016-12-27
    • 2014-10-08
    • 2022-12-03
    • 2015-08-11
    • 2022-08-20
    • 1970-01-01
    • 1970-01-01
    • 2020-04-08
    相关资源
    最近更新 更多