【问题标题】:Using lambda with .apply() in Pandas在 Pandas 中使用 lambda 和 .apply()
【发布时间】:2021-09-18 13:53:14
【问题描述】:

在 Pandas 中,我正在尝试使用 .apply() 应用此 lambda 函数,但出现此错误:'ValueError:Series 的真值不明确。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()'。

我做错了什么?

(beers[:10] - beers.mean()).apply(lambda x: 'low' if x < 0 else 'high')

啤酒是一个系列。

谢谢!

【问题讨论】:

  • 你可以尝试在apply func中添加axis=1参数吗?

标签: python pandas


【解决方案1】:

beers 不是Series 否则你的代码工作得很好。肯定是DataFrame,也可能是只有一列的DataFrame

演示:

>>> beers = pd.Series(np.random.randint(1, 10, 20))

>>> type(beers)
pandas.core.series.Series

>>> (beers[:10] - beers.mean()).apply(lambda x: 'low' if x < 0 else 'high')
0    high
1     low
2    high
3     low
4    high
5    high
6     low
7    high
8    high
9     low
dtype: object

现在如果beersDataFrame

>>> beers = beers.to_frame()

>>> type(beers)
pandas.core.frame.DataFrame

>>> (beers[:10] - beers.mean()).apply(lambda x: 'low' if x < 0 else 'high')
...
ValueError: The truth value of a Series is ambiguous.
Use a.empty, a.bool(), a.item(), a.any() or a.all().

beers只有一列的情况,可以使用squeeze

>>> (beers[:10] - beers.mean()).squeeze().apply(lambda x: 'low' if x < 0 else 'high')
0    high
1     low
2    high
3     low
4    high
5    high
6     low
7    high
8    high
9     low
Name: 0, dtype: object

【讨论】:

    【解决方案2】:

    我认为你想要做的是这个 如果 beers 是一个系列,如果它是一个 df,你还需要列名

    beers_mean = beers.mean()
    beers[:10].apply(lambda x: 'low' if (x-beers_mean)<0 else 'high'
    

    它不能将 beers[:10] - beers.mean() 变成一个新系列,这就是为什么你得到一个例外

    如果 beers 是 DF 并且您想在表中的单个列上执行此操作,那么 刚选的

    beer_col = beers[['col_name']]
    beers_mean = beer_col .mean()
    beer_col[:10].apply(lambda x: 'low' if (x-beers_mean)<0 else 'high'
    

    【讨论】:

      猜你喜欢
      • 2021-10-19
      • 2017-10-04
      • 2019-11-23
      • 1970-01-01
      • 2022-01-11
      • 2021-11-11
      • 2023-02-13
      • 1970-01-01
      • 2018-01-17
      相关资源
      最近更新 更多