gpt4 book ai didi

python - Pandas 数据帧: Add Column Conditionally On Past Dates and Values

转载 作者:行者123 更新时间:2023-11-30 23:33:19 24 4
gpt4 key购买 nike

我正在继续尝试在 pandas 中完成在 excel 中很容易完成的事情。考虑 df:

   |  ID  |  Value  |  Date
0 | A | .21 | 2010-01-01
1 | A | .31 | 2010-02-01
2 | A | .44 | 2010-02-15
3 | B | .23 | 2010-01-01
4 | C | .21 | 2010-02-01
5 | C | .91 | 2010-02-15

关于添加新列的最佳方法的思考,该新列检查 (a) 值是否大于 0.30 以及 (b) ID 是否具有更早日期的记录(行)大于.30?

理想情况下,当值大于 0.3 时,我希望在新列中记录"is",并且这是该 ID 的值大于 0.30 的最早日期;如果该值小于 0.3 并且 ID 没有大于 0.3 的早期记录,则记录“否”;并在 ID 具有值 > .3 的较早记录时记录“已经”。

所以输出看起来像这样:

   |  ID  |  Value  |  Date        | Result 
0 | A | .21 | 2010-01-01 | No
1 | A | .31 | 2010-02-01 | Yes
2 | A | .24 | 2010-02-15 | Already
3 | B | .23 | 2010-01-01 | No
4 | C | .21 | 2010-02-01 | No
5 | C | .91 | 2010-02-15 | Yes

感谢您的任何意见。

最佳答案

这是一种方法,创建一个作用于每个 ID subDataFrame 的函数以返回一系列“否”、"is"和“已经”:

In [11]: def f(x, threshold=0.3):
first = (x > threshold).values.argmax()
if x.iloc[first] > threshold:
return pd.concat([pd.Series('No', x.index[:first]),
pd.Series('Yes', [x.index[first]]),
pd.Series('Already', x.index[first+1:])])
else:
return pd.Series('No', x.index)

In [12]: df.groupby('ID')['Value'].apply(f)
Out[12]:
0 No
1 Yes
2 Already
3 Yes
4 No
5 Yes
dtype: object

In [13]: df['Result'] = df.groupby('ID')['Value'].apply(f)

In [14]: df
Out[14]:
ID Value Date Result
0 A 0.21 2010-01-01 No
1 A 0.31 2010-02-01 Yes
2 A 0.29 2010-02-15 Already
3 B 0.23 2010-01-01 Yes
4 C 0.21 2010-02-01 No
5 C 0.91 2010-02-15 Yes

关于python - Pandas 数据帧: Add Column Conditionally On Past Dates and Values,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18928307/

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