根据熊猫中另一个数据框中的另一列设置值?

时间:2019-05-06 07:24:32

标签: pandas

我具有以下用于映射表的数据框:

mapping_df

component.ts

另一个df作为

export class OrganizationsComponent {

  public organizations;

  constructor(public access: OrganizationService) {

    this.access.getOrganizations().subscribe((data => {
      this.organizations = data;
      console.log(this.organizations);
    }))
   console.log(this.organizations)
}

将df输出为:

    ids     true_id
    [1,2,3] abc1
    [4,7,8] def1

有什么建议吗?

2 个答案:

答案 0 :(得分:1)

通过理解和Series.map创建字典:

d = {k:v for x, v in mapping_df[['ids','true_id']].values for k in x}
print (d)
{1: 'abc1', 2: 'abc1', 3: 'abc1', 4: 'def1', 7: 'def1', 8: 'def1'}

df['true_id'] = df['id'].map(d)
print (df)
   id  name address true_id
0   1   tnu    a123    abc1
1   2    tn     a23    abc1
2   3   tnu   a1234    abc1
3   4   mnu    dd34    def1
4   7  mnuu    dd34    def1
5   8   mna     dd3    def1

答案 1 :(得分:0)

使用df取消嵌套np.repeat

df1 = pd.DataFrame(np.concatenate(df.ids), index=np.repeat(df.true_id, df.ids.str.len()), columns=['id']).reset_index()

Out[575]:
  true_id  id
0    abc1   1
1    abc1   2
2    abc1   3
3    def1   4
4    def1   7
5    def1   8

df1上将another_dfid合并(我假设another_dfid上具有索引。如果没有,只需取出{{ 1}})

reset_index
相关问题