我有一个这样的数据集:
country | year | supporting_nation | eco_sup | mil_sup
------------------------------------------------------------------
Fake 1984 US 1 1
Fake 1984 SU 0 1
在这个假例子中,一个国家在冷战期间扮演着两面派的角色,并得到了双方的支持。
我正在以两种方式重塑数据集:
-
我删除了所有非美苏支持实例,我只对这两个国家感兴趣
-
我想把它减到
1 line per year per country
,这意味着我要为每个变量添加特定于us/su的伪变量。
就像这样:
country | year | US_SUP | US_eco_sup | US_mil_sup | SU_SUP | SU_eco_sup | SU_mil_sup |
------------------------------------------------------------------------------------------
Fake 1984 1 1 1 1 1 1
Fake 1985 1 1 1 1 1 1
florp 1984 0 0 0 1 1 1
florp 1985 0 0 0 1 1 1
我添加了所有的假人和
US_SUP
和
SU_SUP
已用正确的值填充了列。
但是,我在为其他变量提供正确的值时遇到了困难。
为此,我编写了以下函数:
def get_values(x):
cols = ['eco_sup', 'mil_sup']
nation = ''
if x['SU_SUP'] == 1:
nation = 'SU_'
if x['US_SUP'] == 1:
nation = 'US_'
support_vars = x[['eco_sup', 'mil_sup']]
# Since each line contains only one measure of support I can
# automatically assume that the support_vars are from
# the correct nation
support_cols = [nation + x for x in cols]
x[support_cols] = support_vars
这个计划比使用
df.groupby.agg('max')
操作,但作为上面返回的函数,我从未到达此步骤
0
对于每个新的虚拟列,不考虑数据帧中列的值。
所以在最后一张桌子上
US/SU_mil/eco_sup
变量将为0。
有人知道我做错了什么/为什么列得到了错误的值吗?