python - pandas 将个体逻辑应用于群体

标签 python pandas

如果我有一个 pandas 数据框,如下所示:

day id  val
1-Jan   A   -5
2-Jan   A   -4
3-Jan   A   3
1-Jan   B   2
2-Jan   B   1
3-Jan   B   -5

如何添加一个新列,对于具有相同 id 的所有行,如果 val 在 1 月 1 日为负数,则所有行均为“Y”,如果不是,则所有行均为“N”?像这样的东西:

day id  val neg_on_jan_1
1-Jan   A   -5  y
2-Jan   A   -4  y
3-Jan   A   3   y
1-Jan   B   2   n
2-Jan   B   1   n
3-Jan   B   -5  n

我看过 group by 和 apply-lambda 函数,但仍然觉得我错过了一些东西。我刚刚开始接触 pandas,有 SQL 背景,所以如果我的大脑仍然用行和 Oracle 分析函数思考,请原谅我:)

最佳答案

根据 @Ami Tavory 的建议包含 map

gb = df.set_index(['day', 'id']).groupby(level='id')
s = gb.val.transform(lambda s: s.loc['1-Jan'].lt(0)).map({1: 'y', 0:'n'})
s

day    id
1-Jan  A     y
2-Jan  A     y
3-Jan  A     y
1-Jan  B     n
2-Jan  B     n
3-Jan  B     n
Name: val, dtype: object

df.merge(s.to_frame('neg_on_jan_1').reset_index())

enter image description here

关于python - pandas 将个体逻辑应用于群体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39374620/

相关文章:

python - 使用 node.js crypto aes256 加密并使用 python2.7 PyCrypto 解密

Python Pandas 索引错误 : List Index out of range

python - 在 Dask 中使用尚未实现的 Pandas 函数

python - pandas DataFrame.query 表达式,默认返回所有行

python - 根据 Pandas 中的行值创建新列

Python/Pyspark - 如何用平均值替换一些单元格?

python - 使用 Python 2.7 在 Django 1.6 中实现 chartit - TypeError : 'NoneType' has no attribute __getitem__

python-3.x - 根据另一个数据帧中的值查找 Pandas 数据帧中的区间

python - Dict of Dict 到 CSV(带有已定义的 header )

python - 如何将我的 python spyder 与 github 连接?