让我们假设df如下:
import pandas as pd
df = pd.DataFrame(data={'fname':['Anky','Anky','Tom','Harry','Harry','Harry'],'lname':['sur1','sur1','sur2','sur3','sur3','sur3'],'role':['','abc','def','ghi','','ijk'],'mobile':['08511663451212','+4471123456','0851166346','','0851166347',''],'Pmobile':['085116634512','1234567890','8885116634','','+353051166347','0987654321']})
import numpy as np
df.replace('',np.nan,inplace=True)
df:
fname lname role mobile Pmobile
0 Anky sur1 NaN 08511663451212 085116634512
1 Anky sur1 abc +4471123456 1234567890
2 Tom sur2 def 0851166346 8885116634
3 Harry sur3 ghi NaN NaN
4 Harry sur3 NaN 0851166347 +353051166347
5 Harry sur3 ijk NaN 0987654321
因此,我想用mobile
中的值以Pmobile
开头的'08','8','+353
中的值更新列Pmobile
,同时它应该从找到的mobile
字段中删除该值匹配并将数据复制到df.mobile.update(df['Pmobile'][df['Pmobile'].str.startswith(('08','8','+353'),na=False)])
df.Pmobile[df.mobile==df.Pmobile] = np.nan
字段。
目前我是通过以下方式获得的:
fname lname role mobile Pmobile
0 Anky sur1 NaN 085116634512 NaN
1 Anky sur1 abc +4471123456 1234567890
2 Tom sur2 def 8885116634 NaN
3 Harry sur3 ghi NaN NaN
4 Harry sur3 NaN +353051166347 NaN
5 Harry sur3 ijk NaN 0987654321
df:
PasswordSecurity
有没有办法做到这一点?
先谢谢了。 :)
答案 0 :(得分:2)
您可以使用shift
将列向左移动:
In[50]:
df.loc[df['Pmobile'].str.startswith(('08','8','+353'),na=False), ['mobile','Pmobile']] = df[['mobile','Pmobile']].shift(-1,axis=1)
df
Out[50]:
fname lname role mobile Pmobile
0 Anky sur1 NaN 085116634512 NaN
1 Anky sur1 abc +4471123456 1234567890
2 Tom sur2 def 8885116634 NaN
3 Harry sur3 ghi NaN NaN
4 Harry sur3 NaN +353051166347 NaN
5 Harry sur3 ijk NaN 0987654321
因此,请使用条件屏蔽感兴趣的行,然后为满足条件的那两列左移1的结果赋值。
这将使NaN
的值发生变化,而在不满足条件的情况下不做任何事情