2016-10-29 47 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(";")