gpt4 book ai didi

python - pandas apply upper() 分别作用于两个字符串列中的每一个,但不能一起作用

转载 作者:行者123 更新时间:2023-11-28 20:14:17 25 4
gpt4 key购买 nike

我有一个简单的数据框,遵循这些原则:

    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' object has no attribute 'upper'", 'occurred at index a')”。

显然,我想知道如何修复它(即能够同时将两列都大写)。但我也想知道一个列如何可以自己拥有属性“upper”,但是当将 lambda 作为多个列的一部分应用于它时会丢失它。

最佳答案

使用 str 访问器:

df.loc[:,'a':'b'].apply(lambda x: x.str.upper())

输出:

       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

在这种情况下,pandas Series 被传递给函数 f,因此我们可以使用 .str 访问器来调用字符串函数 upper。

现在,让我们来看第一种情况:

def f(x):
print(type(x))
print(type(x[0]))

df.loc[:,'a'].apply(f)

输出:

<class 'str'>
<class 'str'>
<class 'str'>
<class 'str'>

在这里,我们正在使用 pd.Series.apply 并传递每个值本身。因此,我们可以简单地直接在每个值上调用字符串函数 upper。

而且,您还可以将 pd.DataFrame.applymap 用作 @chrisz shows在他的解决方案中将数据帧的每个单元格值传递给函数。

关于python - pandas apply upper() 分别作用于两个字符串列中的每一个,但不能一起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50631468/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com