gpt4 book ai didi

python - 如何应用函数来创建虚拟变量?

转载 作者:行者123 更新时间:2023-11-28 22:19:00 24 4
gpt4 key购买 nike

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

data={'state':[1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4],
'year':[1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3],
'pop':[11, 22, 0, 33, 44, 32, 45, 66, 34, 12, 32, 0],
'gdp':[123, 341, 554, 654, 245, 665, 332 ,321, 344, 232, 542, 221]}
frame=pd.DataFrame(data)

def treat(group):
if group.ix[group.year==3, 'pop']!=0:
group['Treated']=1
else:
group['Treated']=0

frame.groupby('state').apply(treat)

我正在尝试根据某些条件创建变量 frame['Treated']if ('year'==3) and ('pop'!=0) - 我认为 'state' 在 Treated 组中(所以我创建了一个名为 'Treated' 的变量)。

不幸的是,我遇到了一个错误:

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

我的代码有什么问题?你知道我如何解决这个问题吗?

重新编辑感谢您的友好回答,很抱歉没有清楚地描述我的问题。

我正在尝试再次描述我的问题。对于state 1,第3年的pop为0,所以state 1不在治疗组中(如下所示,frame['Treated']=0 for state 1 in every year)对于state 2,pop在第3年不等于0,所以state 2在treated组中(如下图,每年state 2的frame['Treated']=1)其他州出于类似原因进行处理。最终结果如下。

    state  year  pop  gdp  Treated
0 1 1 11 123 0
1 1 2 22 341 0
2 1 3 0 554 0
3 2 1 33 654 1
4 2 2 44 245 1
5 2 3 32 665 1
6 3 1 45 332 1
7 3 2 66 321 1
8 3 3 34 344 1
9 4 1 12 232 0
10 4 2 32 542 0
11 4 3 0 221 0

最佳答案

groupby 这里不需要,你只需要 np.where

frame['Treated']=np.where((frame.year==3)&(frame.pop!=0),1,0)
frame
Out[429]:
gdp pop state year Treated
0 123 11 1 1 0
1 341 22 1 2 0
2 554 0 1 3 1
3 654 33 2 1 0
4 245 44 2 2 0
5 665 32 2 3 1
6 332 45 3 1 0
7 321 66 3 2 0
8 344 34 3 3 1
9 232 12 4 1 0
10 542 32 4 2 0
11 221 0 4 3 1

关于python - 如何应用函数来创建虚拟变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50093238/

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