基于其他列熊猫的相同值的列的数学运算

时间:2019-04-18 11:27:53

标签: python pandas dataframe

我的第一个数据框是:

df1 =     


    A        B
    61880    7
    62646    8
    62651    9
    62656    10
    62783    11

我的第二个数据帧是:

df2 =

    C        D
    62783    2
    62646    3
    61880    4
    62656    5
    62651    6

正如您在第一个和第二个数据帧中看到的那样,我们有具有相同值的列,其bun的顺序不同(!)(col A and col C)

所需的输出是: 从具有相同“ A”和“ C”值的行中获取所有“ B”和“ D”值,并对它们进行数学运算(例如,B除以D)。

示例: 2 + 11(在“ A”和“ C”列中它们的值都为62783)

添加!编辑!

非常感谢!我遇到了另一个我忘记提及的问题:

有时,在“ A”列中,我有相同的值,例如,我们可以两次看到“ 61880”,依此类推:

df1 =

A        B
*61880*    7
**62646**    8
62651    9
62656    10
62783    11
*61880*    3
**62646**    2

我想通过考虑以下因素来执行您提到的BUT相同的过程:

我想基于“ B”的值,即“ B”的总和对列“ A”进行排序。像这样:

 61880    7+3
 62646    8+2
 ...

我用data.groupby('mm_fid')['vel'].sum()完成了操作,但是结果之后却无法执行操作。因此,我想创建一个总和为“ B”的唯一列,然后继续提供您提供的答案!

2 个答案:

答案 0 :(得分:3)

您需要一个merge,然后只需添加相应的值即可:

res = df1.merge(df2, left_on='A', right_on='C')
(res.B + res.D).to_frame('result').set_index(res.A)

        result
A            
61880      15
62646      14
62651      21
62656      20
62783      15

答案 1 :(得分:1)

我相信您需要DataFrame.addDataFrame.set_index

Schema::create('questions', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('title');
            $table->string('slug')->unique();
            $table->text('body');
            $table->unsignedInteger('views')->default(0);
            $table->unsignedInteger('answers')->default(0);
            $table->integer('votes')->default(0);
            $table->unsignedInteger('best_answer_id')->nullable();
            $table->unsignedInteger('user_id');
            $table->timestamps();
        });

        Schema::table('questions', function (Blueprint $table) {
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
        });

另一种解决方案是将concat与聚合df3 = df1.set_index('A')['B'].add(df2.set_index('C')['D'], fill_value=0).reset_index() df3.columns = ['A','B'] print (df3) A B 0 61880 11 1 62646 11 2 62651 15 3 62656 15 4 62783 13 一起使用:

sum