2016-12-28 36 views
3

我有一個數據框內的列,我需要更新,如果另一列是空的。該列是'subscriberkey'並且已經有值。我需要用字符串+數字來更新這些值。我的意圖不是創建一個重複的列。添加字符串+自動遞增 - 熊貓,python

該值需要是唯一的,因此我最初認爲追加字符串+數字是最好的選擇。

Age Email   Subscriberkey 
10 [email protected] giririfndfieir 
23     kfkkfkfffrrrc 
64 [email protected] ifiririieiriei  

第二行,我會想subscriberkey是字符串+數字+字符串 到目前爲止,我已經試過如下:

df.loc[df.Email == NULL, 'subscriberkey']= 'string'+.cumcount()+1+'string' 

我會很高興就如何最好地實現指針這個。

+2

,你得到什麼錯誤? 你能把一個可重複的例子放在一起嗎? – PabTorre

+0

我將編輯我的問題以反映這一點。 –

+0

我已經編輯了我的問題 –

回答

4

您可以嘗試這樣的事:

nullCond = df.Email.isnull()  
# or nullCond = (df.Email == "") it those are empty strings 

df.loc[nullCond, 'Subscriberkey'] = "string" + nullCond[nullCond].cumsum().astype(str) + "string" 

enter image description here

+0

感謝您對此有所瞭解。當我嘗試它時出現錯誤:**不能將'list'對象隱式轉換爲str ** –

+0

更新了類型轉換部分。需要用'astype()'將int轉換爲str,你可以檢查它是否有效。 – Psidom

+0

感謝您的回答。這很好。我有一個稍微不同的要求。不知道是否要開一個新的問題。假設我想標記訂戶鍵的所有列,以給出字符串+數字ie。沒有條件,我會怎麼做呢? –

0

考慮df

df = pd.DataFrame(dict(EMAIL_ACQ_DT=['key1', None, 'key2', None, 'ke3', 'key4', None, None])) 
print(df) 

    EMAIL_ACQ_DT 
0   key1 
1   None 
2   key2 
3   None 
4   ke3 
5   key4 
6   None 
7   None 

fill_keys = df.groupby(df.EMAIL_ACQ_DT.isnull()).cumcount().apply('key{}_'.format) 
df['subscriberkey'] = df.EMAIL_ACQ_DT.fillna(fill_keys) 
print(df) 

    EMAIL_ACQ_DT subscriberkey 
0   key1   key1 
1   None   key0_ 
2   key2   key2 
3   None   key1_ 
4   ke3   ke3 
5   key4   key4 
6   None   key2_ 
7   None   key3_ 
+0

好奇,如果這是來自Responsys? –

+0

@Data_Kid我不知道你在說什麼......所以我猜不是:-) – piRSquared