2016-10-29 48 views
3

我有如下一個數據幀:怎麼做字符串操作上的熊貓數據幀

df = pd.DataFrame({'a': [10, 11, None], 
        'b': ['apple;', None, 'orange;'], 
        'c': ['red', 'blue', 'green']}) 

我試圖剝離「;」這些字符串。我試圖

df.select_dtypes(include=['object']).applymap(lambda x: x.strip(';')) 

我收到錯誤消息:

AttributeError: ("'NoneType' object has no attribute 'strip'", 'occurred at index b') 

好像沒有人給我一些麻煩。非常感謝幫助。非常感謝。

回答

1

的問題是,一些值是None,你不能Non.strip()

df.select_dtypes(include=['object']) 
     b  c 
0 apple; red 
1  None blue 
2 orange; green 

你可以做的是strip只有當對象不是無,否則只返回對象:

df.select_dtypes(include=['object']).applymap(lambda x: x.strip(';') if x else x) 
     b  c 
0 apple red 
1 None blue 
2 orange green 
+1

用'拉姆達X上的問題:x.strip(「;」)如果x其他x'是,你將有attribu與其他在Python中有錯誤的對象相關的錯誤,也缺少'.strip'方法。如果你想通過第一次測試,你可以做'lambda x:x.strip(';')if hasattr(x,'strip')else x'。 – dawg

+1

@dawg,正確。由於示例中的數據僅包含字符串,所以'if x'就足夠了。另一種方法是檢查'if type(x)== str',確保'strip'只在字符串上(而不在其他可能有strip函數的對象上,我們不確定它會返回預期結果結果)。 – Dekel

+0

這是完美的。非常感謝! – zesla

1

在這種情況下,您可以使用tryexcept

>>> def am(o): 
... try: 
...  return o.strip(';') 
... except AttributeError: 
...  return o 

然後applymap你曾嘗試:

>>> df.select_dtypes(include=['object']).applymap(am) 
     b  c 
0 apple red 
1 None blue 
2 orange green 
0

使用系列str屬性和apply,而不是applymap

In [17]: df.select_dtypes(include=['object']).apply(lambda S:S.str.strip(';')) 
Out[17]: 
     b  c 
0 apple red 
1 None blue 
2 orange green 

In [18]: 
0

另一種辦法是通過所有的都是dtype對象和使用的列進行迭代該系列功能strip,處理NaN值:

for col in df.columns[df.dtypes == object]: 
    df[col] = df[col].str.strip(";")