简体   繁体   English

在pandas df中合并特定值

[英]Merge specific values in a pandas df

I'm currently merging the first and last string in a row . 我目前合并第一和最后一个stringrow These strings are merged when they are to the right of a specific value. 这些strings在特定值的右侧时将合并。 I'm hoping to change that to below a specific value. 我希望将其更改为特定值以下。

import pandas as pd

d = ({
    'A' : ['X','Foo','','X','Big'],           
    'B' : ['No','','','No',''],
    'C' : ['Merge','Bar','','Merge','Cat'],
    })

df = pd.DataFrame(data = d)

m = df.A == 'X'

def f(x):
    s = x[x!= '']
    x[s.index[1]] = x[s.index[1]] + ' ' + x[s.index[-1]]
    x[s.index[-1]] = ''
    return x

df = df.astype(str).mask(m, df[m].apply(f, axis=1))

This code merges the first and last string when followed by X . 此代码在后面跟有X时合并第一个和最后一个string

Output: 输出:

     A         B    C
0    X  No Merge     
1  Foo            Bar
2                    
3    X  No Merge     
4  Big            Cat

I'm hoping to change it to rows beneath the value X . 我希望将其更改为值X以下的rows

Intended Output: 预期输出:

         A   B      C
0        X  No  Merge
1  Foo Bar           
2                    
3        X  No  Merge
4  Big Cat

Solution is very similar, only boolean mask is shifted and first NaN is replaced to False and also indices from [1] are changed to [0] for seelct first value (of column A ): 解决方案非常相似,只有布尔掩码被移位,并且将第一个NaN替换为False并且对于(第AA )明显的第一个值,从[1]索引也更改为[0]

m = (df.A == 'X').shift().fillna(False)

def f(x):
    s = x[x!= '']
    x[s.index[0]] = x[s.index[0]] + ' ' + x[s.index[-1]]
    x[s.index[-1]] = ''
    return x

df = df.astype(str).mask(m, df[m].apply(f, axis=1))
print (df)
         A   B      C
0        X  No  Merge
1  Foo Bar           
2                    
3        X  No  Merge
4  Big Cat        

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM