简体   繁体   English

如何在熊猫df列中合并特定值

[英]How to merge specific values in pandas df column

I'm sure this problem would be somewhere in SO but I can't find it anywhere. 我敢肯定这个问题会在SO但我找不到任何地方。 How can you merge specific values in a pandas column ? 如何在pandas column merge特定值? For the df below I only want to merge values in Col A,B when they are Foo,Bar and leave everything else. 对于下面的df ,我只想在Col A,B值分别为Foo,Barmerge它们Foo,Bar并保留其他所有内容。

import pandas as pd

d = ({
    'A' : ['Foo','No'],
    'B' : ['Bar','Bar'],
   })

df = pd.DataFrame(data=d)

If I do this: 如果我这样做:

df["A"] = df["A"].map(str) + df["B"] 

        A    B
0  FooBar  Bar
1   NoBar  Bar

Where as I'm hoping to output: 我希望在哪里输出:

        A    B
0  FooBar     
1      No  Bar

IIUC, IIUC,

idx=(df.A == 'Foo' )& (df.B == 'Bar')
df.loc[idx, 'A']  = df.loc[idx, 'A'] + df.loc[idx, 'B']
df.loc[idx, 'B'] = ''

    A       B
0   FooBar  
1   No      Bar

Use: 采用:

mask = (df[['A', 'B']].values == ['Foo','Bar']).all(axis=1)

df['A'] = np.where(mask, df["A"] + df["B"], df['A'])
df['B'] = np.where(mask, '', df["B"])
print (df)

        A    B
0  FooBar     
1      No  Bar

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

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