如何正确合并两个pandas数据帧

时间:2018-05-24 11:58:37

标签: pandas dataframe merge

我有2个数据帧

DF1

DELETE

df2

@foreach($students as $model)
<tr>
    <td>{{ $key + $models->firstItem() }}</td>
    <td>{{ $model->name }}</td>
    <td>{{ $model->email }}</td>
    <td>{{ $model->roll_no }}</td>
    <td>{{ $model->StudentDetail->phone }}</td>
    <td>{{ $model->StudentDetail->course }}</td>
    <td>{{ $model->StudentDetail->city }}</td>
    <td>{{ $model->StudentDetail->state->state_name }}</td>
    <td>
        <a href="#">Edit</a> |

        <a href="javascript:void(0);" onclick="event.preventDefault();document.getElementById('delete_form').submit();">DELETE</a>

       <form id="delete_form" style="display:none" action="{{ route('student.destroy',$model->id)}}" method="POST" >
          {{ csrf_field() }}   
           <input type="hidden" name="_method" value="delete" />
        </form>
    </td>
</tr>
@endforeach

我想在这做两件事。

首先,我想检查df1中的所有唯一代码是否存在于df2

其次,我想通过代码合并这两个df2

df3,应该看起来像

Code  Sales  Store
A       10   alpha
B        5   beta
C        4   gamma
B        3   alpha

我做了

Code   Unit_Price  
A          2       
B          3     
C          4
D          5
E          6

不确定我是否正确,我将非常感谢您花时间和精力帮助我完成此记录

1 个答案:

答案 0 :(得分:1)

需要numpy.setdiff1d列表的检查成员资格唯一值:

print (np.setdiff1d(df1['Code'].unique(), df1['Code'].unique()))
[]

print (np.setdiff1d(df2['Code'].unique(), df1['Code'].unique()))
['D' 'E']

您的解决方案很好,特别是如果需要添加更多列,例如:

print (df2)
  Code  Unit_Price  col
0    A           2    7
1    B           3    2
2    C           4    1
3    D           5    0
4    E           6    3

df3 = df1.merge(df2,on='Code',how='left')
print (df3)
  Code  Sales  Store  Unit_Price  col
0    A     10  alpha           2    7
1    B      5   beta           3    2
2    C      4  gamma           4    1
3    B      3  alpha           3    2

如果需要,只需添加一列就可以Series使用df1['unit_price'] = df1['Code'].map(df2.set_index('Code')['Unit_Price']) print (df1) Code Sales Store unit_price 0 A 10 alpha 2 1 B 5 beta 3 2 C 4 gamma 4 3 B 3 alpha 3 更快的内容:

angular.module("app",[]).controller("optionCtrl", function($scope) {
  $scope.form = {};
  $scope.form.language_id = 2;
  $scope.langs = [
  { id: 1,languageTitle: 'Eng' },
  { id: 2,languageTitle: 'Swe' },
  { id: 3,languageTitle: 'Fra' }
  ];
});