首页 文章

从pandas中的2个数据框中添加2列[重复]

提问于
浏览
1

这个问题在这里已有答案:

我是熊猫的新手,你能不能帮助我,我有2个DF:

df1 = pd.DataFrame({'A': ['name', 'color', 'city', 'animal'], 'number': ['1', '32', '22', '13']})

df2 = pd.DataFrame({'A': ['name', 'color', 'city', 'animal'], 'number': ['12', '2', '42', '15']})

df1
    A       number
0   name    1
1   color   32
2   city    22
3   animal  13
DF1
    A       number
0   name    12
1   color   2
2   city    42
3   animal  15

我需要得到列数的总和,例如

DF1
    A       number
0   name    13
1   color   34
2   city    64
3   animal  27

但如果我做新= df1 df2我得到了

NEW
    A             number
0   namename        13
1   colorcolor      34
2   citycity        64
3   animalanimal    27

我甚至尝试合并=“A”但没有 . 任何人都可以请我帮忙请谢谢

2 回答

  • 0

    这有两种不同的方式:一种是add,另一种是 concatgroupby . 在任何一种情况下,您都需要确保 number 列是数字的(您的示例数据帧具有字符串):

    # set `number` to numeric (could be float, I chose int here)
    df1['number'] = df1['number'].astype(int)
    df2['number'] = df2['number'].astype(int)
    
    # method 1, set the index to `A` in each and add the two frames together:
    df1.set_index('A').add(df2.set_index('A')).reset_index()
    
    # method 2, concatenate the two frames, groupby A, and get the sum:
    pd.concat((df1,df2)).groupby('A',as_index=False).sum()
    

    Output:

    A  number
    0  animal      28
    1    city      64
    2   color      34
    3    name      13
    
  • 0

    合并并不是一个坏主意,您只需要记住将数字系列转换为数字,选择要合并的列,然后通过select_dtypes对数字列求和:

    df1['number'] = pd.to_numeric(df1['number'])
    df2['number'] = pd.to_numeric(df2['number'])
    
    df = df1.merge(df2, on='A')
    df['number'] = df.select_dtypes(include='number').sum(1)  # 'number' means numeric columns
    df = df[['A', 'number']]
    
    print(df)
    
            A  number
    0    name      13
    1   color      34
    2    city      64
    3  animal      28
    

相关问题