如何解决使用If-else更改熊猫中的值
我的pd df由三列组成:ID
,t
和ind1
。
import pandas as pd
dat = {'ID': [1,1,2,3,4,5,6,6],'t': [0,2],'ind1' : [1,0]
}
df = pd.DataFrame(dat,columns = ['ID','t','ind1'])
print (df)
我需要做的是创建一个新列(res
)
- 对于所有
ID
和ind1==0
,则res
为零。 - 对于所有
ID
ind1==1
,如果t==max(t)
(按ID
分组),则res
= 1,否则为零。
这是预期的输出
解决方法
先用groupby
和idxmax
进行检查,然后用where
transform
进行all
df['res']=df.groupby('ID').t.transform('idxmax').where(df.groupby('ID').ind1.transform('all')).eq(df.index).astype(int)
df
Out[160]:
ID t ind1 res
0 1 0 1 0
1 1 1 1 0
2 1 2 1 0
3 1 3 1 1
4 2 0 0 0
5 2 1 0 0
6 2 2 0 0
7 3 0 0 0
8 3 1 0 0
9 3 2 0 0
10 3 3 0 0
11 4 0 1 0
12 4 1 1 0
13 4 2 1 1
14 5 0 1 0
15 5 1 1 1
16 6 0 0 0
17 6 1 0 0
18 6 2 0 0
,
这是基于import { greeting } from './auxiliary.js'
列已排序的情况下进行的:
ID
,
使用groupby.apply
:
df['res'] = (df.groupby('ID').apply(lambda x: x['ind1'].eq(1)&x['t'].eq(x['t'].max()))
.astype(int).reset_index(drop=True))
print(df)
ID t ind1 res
0 1 0 1 0
1 1 1 1 0
2 1 2 1 0
3 1 3 1 1
4 2 0 0 0
5 2 1 0 0
6 2 2 0 0
7 3 0 0 0
8 3 1 0 0
9 3 2 0 0
10 3 3 0 0
11 4 0 1 0
12 4 1 1 0
13 4 2 1 1
14 5 0 1 0
15 5 1 1 1
16 6 0 0 0
17 6 1 0 0
18 6 2 0 0
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。