2016-11-04 43 views
0

我有一個包含電子郵件的列的熊貓數據幀創建從一個特定字符的索引的熊貓數據幀新列:另一列

Email 
[email protected] 
[email protected] 
[email protected] 
[email protected] 

此列/系列的數據類型是UNICODE,它似乎不適合我想要做的事情。我希望得到的是剛剛在海峽格式的電子郵件域的一列,這樣的事情:

Domain 
gmail.com 
yahoo.com 
aol.com 
hrc.com 

我也試着這樣做:

df['domain'] = df['Email'][:,df['Email'].find('@'):]

,但我得到一個屬性錯誤:''Series'對象沒有屬性'find''。

我已經遍佈堆棧溢出搜索,但只找到基於單個選定的整數選擇子字符串的方式,但這不適用於這種情況,因爲'@'的位置在每個實例中是不同的。我真的想避免使用for循環來做到這一點。有沒有人知道一個簡單的方法來完成這個?我認爲UNICODE數據類型可能會產生干擾。

編輯: 當我創建一個單獨的環境(IPython的)樣本數據,但在Databricks(Python中2.7.10),用它在桌子上的@rojeeer提供的解決方案的偉大工程,我公司不斷得到錯誤:

TypeError: split() got an unexpected keyword argument 'return_type' 
TypeError: split() got an unexpected keyword argument 'expand' 

我相信這是由於我的表中的數據編碼爲Unicode(或未編碼)的事實。我試過幾件事情將其轉換爲STR:

df[‘email’] = df[‘email’].map(lambda x: x.encode("utf-8")) 
df[‘email’] = df[‘email’].encode("utf-8") 

我還試圖通過嘗試這些方法以標準化數據:

import unicodedata as ucd 
df[‘email’] = ucd.normalize('NFKD', df[‘email’]) 

import unicodedata as ucd 
df[‘email’] = ucd.normalize('NFKD', df[‘email’]).encode(‘ascii’,’ignore’) 

import unicodedata as ucd 

df[‘email’]= df[‘email’].map(lambda x: ucd.normalize('NFKD', x)) 

這些不斷返回錯誤:

AttributeError: 'NoneType' object has no attribute 'encode' 
TypeError: must be unicode, not None 

如何將此係列轉換爲str?

回答

0

在Pandas中,str功能不能直接調用,您需要將其稱爲df.str.function,請參閱Working with text

對於您的應用程序,我認爲兩種功能可能是您的選擇:str.splitstr.extractSeriesstr.splitsplitstr非常相似,它們用正則明文分隔符分割字符串。而str.extract更強大的指定如何提取。

下面是一個示例代碼:

In [16]: df['Email'].str.split('@', expand=True) 
Out[16]: 
     0   1 
0 kitty gmail.com 
1  cat yahoo.com 
2  dog aol.com 
3 person hrc.com 

expand=True將擴大到Series包含DataFrame一樣多的列的分割結果的長度。

希望這會有所幫助。

+0

太棒了!謝謝。 – Naim