[英]How to conditionally concat 2 columns in Python Pandas Dataframe
[英]Conditionally concat a dataframe in python using pandas
我有一個數據框
DF
A B
0 test1 1
1 test2 4
2 test3 1
3 test4 2
DF1
C
0 test3
1 test5
我想有條件地將它們合並到一個新的數據幀
DF2
A B
0 test1 1
1 test2 4
2 test3 0
3 test4 2
4 test5 0
一個新的數據框,如果A列中的值等於C列,那么合並時只需將其B列值更新為默認值0,如果A列中沒有值,則等於a C列中的值只是將其添加到數據框中,如上所示,默認值為0。
df2 = pd.merge(df,df1,left_on='A',right_on='C',how="outer")
df2['A'].fillna(value=df2['C'],inplace=True)
df2.loc[df2['A'] == df2['C'],'B'] = 0
df2 = df2[['A','B']]
我更喜歡下面的選項,但它並不是你要求的。
df1['B'] = 0
df1.columns = ['A','B']
df2 = pd.concat([df,df1])
df2.drop_duplicates('A',take_last=True,inplace=True)
df2 = df2.sort('A').reset_index(drop=True)
您可以在A
和C
列上進行outer
合並
In [31]: tmp = df.merge(df1, left_on='A', right_on='C', how='outer')
從列C
替換列A
nan值
In [32]: tmp['A'].fillna(value=tmp['C'], inplace=True)
然后替換C
值不為空的B
值。
In [33]: tmp.ix[tmp['C'].notnull(), 'B'] = 0
In [34]: tmp[['A', 'B']]
Out[34]:
A B
0 test1 1
1 test2 4
2 test3 0
3 test4 2
4 test5 0
這是一個簡單的方法。 你只需要元件從所述第二數據幀col C
其不是在col A
在第一數據幀-以及通過缺失值設置為串聯0
。 最后你在groupby
中使用一個小的hack,以防col A
有幾個相同的值,以選擇一個0
:
pd.concat([df,df1.rename(columns={'C':'A'})]).fillna(0).groupby('A', as_index=False).last()
A B
0 test1 1
1 test2 4
2 test3 0
3 test4 2
4 test5 0
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.