[英]how do i 'update' a df based on the values of another dataframe that shares a common key? python
how do i 'update' a12 based on the values of another dataframe that shares a common key? 如何基于共享公用密钥的另一个数据框的值“更新” a12? In the example below, the common key is column a.
在下面的示例中,公用密钥为列a。
a12 = a12 =
a b c
0 1 1
1 na na
try10 = try10 =
a b c
1 1 1
when i use a merge, I get something like this. 当我使用合并时,我得到这样的东西。
pd.merge(a12, try10) = pd.merge(a12,try10)=
a b c b_y c_y
0 1 1 na na
1 na na 1 1
I decided to do it manually, but i'm thinking there must be a more pythonic way than the below. 我决定手动执行此操作,但我认为必须有一种比以下方法更加Python化的方法。 I'd appreciate your help.
多谢您的协助。
for i, val in a12.iterrows():
for x, xval in try10.iterrows():
if xval['Firm1'] == val['Firm']:
try10.ix[x]['AMranking'] = val['AMranking']
try10.ix[x]['numlawyers'] = val['numlawyers']
try10.ix[x]['grossprofits'] = val['grossprofits']
del try12['firm']
You can just apply dropna
to a12
before merge
: 您可以在
merge
之前merge
dropna
应用于a12
:
In [53]:
a12 = pd.DataFrame({'a':[0, 1], 'b':[1, np.nan], 'c':[1, np.nan]})
try10= pd.DataFrame({'a':[1], 'b':[1], 'c':[1]})
In [54]:
print pd.merge(a12, try10, how='outer', left_on='a', right_on='a')
a b_x c_x b_y c_y
0 0 1 1 NaN NaN
1 1 NaN NaN 1 1
In [55]:
print pd.merge(a12.dropna(0), try10, how='outer')
a b c
0 0 1 1
1 1 1 1
If a
is the index: 如果
a
是索引:
In [57]:
print pd.merge(a12.dropna(0).reset_index(), try10.reset_index(), how='outer').set_index('a')
b c
a
0 1 1
1 1 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.