我有如下一個數據幀:怎麼做字符串操作上的熊貓數據幀
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')
好像沒有人給我一些麻煩。非常感謝幫助。非常感謝。
用'拉姆達X上的問題:x.strip(「;」)如果x其他x'是,你將有attribu與其他在Python中有錯誤的對象相關的錯誤,也缺少'.strip'方法。如果你想通過第一次測試,你可以做'lambda x:x.strip(';')if hasattr(x,'strip')else x'。 – dawg
@dawg,正確。由於示例中的數據僅包含字符串,所以'if x'就足夠了。另一種方法是檢查'if type(x)== str',確保'strip'只在字符串上(而不在其他可能有strip函數的對象上,我們不確定它會返回預期結果結果)。 – Dekel
這是完美的。非常感謝! – zesla