我有一个简单的数据框架,大致如下:
a b
0 horse cat
1 dog elephant跑步:
df.loc[:,'a'].apply(lambda x: x.upper())或
df.loc[:,'b'].apply(lambda x: x.upper())获取相应列中的动物。然而,运行
df.loc[:,'a':'b'].apply(lambda x: x.upper())或
df.loc[:,['a','b']].apply(lambda x: x.upper())结果在"AttributeError:("'Series‘对象没有属性'upper'",’发生在索引‘’)“。
显然,我想知道如何修复它(即,能够同时大写两列)。但是,我也想知道一个列如何能够自己拥有属性'upper‘,但是当lambda作为多列的一部分应用到它时,它就会丢失。
发布于 2018-05-31 19:32:09
使用str访问器:
df.loc[:,'a':'b'].apply(lambda x: x.str.upper())OUtput:
a b
0 HORSE CAT
1 DOG ELEPHANT这里发生什么事情?
好的,让我们做一个小小的调试:
def f(x):
print(type(x))
print(type(x[0]))
df.loc[:,'a':'b'].apply(f)输出:
<class 'pandas.core.series.Series'>
<class 'str'>
<class 'pandas.core.series.Series'>
<class 'str'>这里我们使用的是pd.DataFrame.apply。
在这种情况下,熊猫系列传递给函数f,因此我们可以使用.str访问器调用string函数。
现在,让我们看一下第一种情况:
def f(x):
print(type(x))
print(type(x[0]))
df.loc[:,'a'].apply(f)输出:
<class 'str'>
<class 'str'>
<class 'str'>
<class 'str'>在这里,are使用pd.Series.apply并传递每个值本身。因此,我们可以直接在每个值上调用string函数。
而且,您还可以在解决方案中使用pd.DataFrame.applymap作为@chrisz shows将数据的每个单元格值传递给函数。
发布于 2018-05-31 19:30:40
使用applymap以便:
向DataFrame应用一个函数,该函数的目的是按元素操作,例如对DataFrame中的每个系列执行映射(func,series)
df[['a', 'b']].applymap(lambda x: x.upper())
a b
0 HORSE CAT
1 DOG ELEPHANThttps://stackoverflow.com/questions/50631468
复制相似问题