Dataframe Append vs pandas Concat [duplicate]

cl25kdpy  于 2023-11-15  发布在  其他
关注(0)|答案(1)|浏览(89)

此问题在此处已有答案

How to replace pandas append with concat?(3个答案)
4天前关闭。
我试图添加到一个嵌套框架,它是工作,但我不得不使用旧版本的python来做到这一点。我没有使用pd.concat那么多在过去。我不确定如何格式化我的代码,使它输出相同的嵌套框架,它与添加。

def new_df(df):
    Employee = []
    PayItem = ['E01', 'E40', 'E41', 'E42']
    Hours = []
    Dollars = []
    new = pd.DataFrame(columns = ['Key', 'PayItem', 'Hours', 'Dollars'])

    Employee = df.loc[0:27,'Employee Number']
    Key = Employee.values.tolist()
    Hours = df.loc[0:27,'Working Hours']

    for i in range(28):
        ok = []
        ok.append(np.nan)
        ok.append(df.loc[i, 'Product Commissions'])
        ok.append(df.loc[i, 'Membership Commissions'])
        ok.append(df.loc[i, 'Tips'])
        Dollars.append(ok)

    for i in range(len(Dollars)):
        for j in range(0,1):
            new = new.append({'Key' : Employee[i], 'PayItem' : PayItem[0], 'Hours': Hours[i],  'Dollars': Dollars[i][j]}, ignore_index=True)
            new = new.append({'Key' : Employee[i], 'PayItem' : PayItem[1], 'Hours': ' ', 'Dollars': Dollars[i][j+1]}, ignore_index=True)
            new = new.append({'Key' : Employee[i], 'PayItem' : PayItem[2], 'Hours': ' ', 'Dollars': Dollars[i][j+2]}, ignore_index=True)
            new = new.append({'Key' : Employee[i], 'PayItem' : PayItem[3], 'Hours': ' ', 'Dollars': Dollars[i][j+3]}, ignore_index=True)
        
    return new

字符串
我尝试使用pandas concat,但我的格式不正确,没有得到相同的结果。

o4tp2gmn

o4tp2gmn1#

pd.concat()连接了两个panda嵌套框架。所以你需要先用你的新条目设置一个嵌套框架。手工构建ok可能更容易。所以像这样:

def new_df(df):
    PayItem = ['E01', 'E40', 'E41', 'E42']
    new = pd.DataFrame(columns=['Key', 'PayItem', 'Hours', 'Dollars'])

    Employee = df.loc[0:27, 'Employee Number']
    Hours = df.loc[0:27, 'Working Hours']

    for i in range(28):
        ok = [np.nan, df.loc[i, 'Product Commissions'], df.loc[i, 'Membership Commissions'], df.loc[i, 'Tips']]
        Dollars = ok

        data = {'Key': [Employee[i]] * len(PayItem),
            'PayItem': PayItem,
            'Hours': [Hours[i]] * len(PayItem),
            'Dollars': Dollars}

        new = pd.concat([new, pd.DataFrame(data)], ignore_index=True)

return new

字符串

相关问题