首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用相同的键值合并Dataframe中的多行

使用相同的键值合并Dataframe中的多行
EN

Stack Overflow用户
提问于 2019-03-15 08:31:53
回答 1查看 520关注 0票数 0

我有一个看起来像这样的数据结构:

代码语言:javascript
复制
idtenifier    amount    dist_type    new_value    new_value2
1              1.0       normal
1              2.0      new_value
1              1.0      new_value2    
3              1.0       normal    
5              3.0       normal    
5              23.0     new_value2    
2              1.0       normal

我希望得到这样的结构:

代码语言:javascript
复制
idtenifier    amount    dist_type    new_value    new_value2
1              1.0       normal         2.0          1.0  
3              1.0       normal                      23.0    
5              3.0       normal     
2              1.0       normal

我有一种感觉,我试图这样做是非常低效的,我甚至不能在列中赋值

代码语言:javascript
复制
df['new_value'] = np.nan

for idx, row in df.iterrows():
    identifier = row['identifier']
    dist_type = row['dist_type']
    amount = row['amount']
    if idx > 0 and identifier == df.loc[idx-1, 'identifier']:
        print(dist_type)
        if dist_type == 'new_value':
            df.loc[idx-1, 'new_value'] == amount
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-03-15 08:42:00

在这里我们不需要使用for循环,在将数据帧一分为二之后,对于dist_type不等于normal,我们执行pivot,然后merge它回来

代码语言:javascript
复制
df1=df.loc[df.dist_type=='normal'].copy()
df2=df.loc[df.dist_type!='normal'].copy()
yourdf=df1.merge(df2.pivot('idtenifier','dist_type','amount').reset_index(),how='left')
yourdf
Out[33]: 
   idtenifier  amount dist_type  new_value  new_value2
0           1     1.0    normal        2.0         1.0
1           3     1.0    normal        NaN         NaN
2           5     3.0    normal        NaN        23.0
3           2     1.0    normal        NaN         NaN
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55173951

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档