熊猫:如何基于同一数据帧中的数据创建列?

时间:2020-01-31 14:47:03

标签: python pandas

我有一个类似于

的Pandas数据框
d = {'id': [1, 2, 2, 3], 'year': [2010, 2010,2011,2010], 'type' : ['A','B','B','A'], 'value': [20,2,8,3]}
df = pd.DataFrame(data = d)

那是

   id  year type  value
0   1  2010    A     20
1   2  2010    B      2
2   2  2011    B      8
3   3  2010    A      3

我想添加一个新列,该列包含一年后相同的idtype的值,如果它存在于df中(否则为0)。也就是说,预期结果是

   id  year type  value  new_value
0   1  2010    A     20   0
1   2  2010    B      2   8
2   2  2011    B      8   0
3   3  2010    A      3   0

我不知道这样做的方法(我一直在尝试应用apply)。有什么建议吗?

3 个答案:

答案 0 :(得分:3)

您可以尝试合并:

(df.merge(df.assign(year=df['year']-1)[['id','year','value']],
          on=['id','year'],
          how='left',
          suffixes=['','_y'])
   .fillna(0)
)

输出:

   id  year type  value  value_y
0   1  2010    A     20      0.0
1   2  2010    B      2      8.0
2   2  2011    B      8      0.0
3   3  2010    A      3      0.0

答案 1 :(得分:0)

您可以使用方法shift

# first, you need to sort by id, type and year (already sorted in example)
df = df.sort_values(['id', 'type', 'year'])
cols = ['id', 'type']

mask = (df[cols].shift(-1, fill_value=False) == df[cols]).all(axis=1)
df['value'].shift(-1, fill_value=0).where(mask, 0)

输出:

0    0
1    8
2    0
3    0
Name: value, dtype: int64

答案 2 :(得分:0)

这是涉及字典的另一种解决方案。

# Creating a key column
df['key'] = df[['id','year','type']].astype(str).sum(axis=1)
print(df)
       id  year type  value     key
    0   1  2010    A     20  12010A
    1   2  2010    B      2  22010B
    2   2  2011    B      8  22011B
    3   3  2010    A      3  32010A

现在,创建字典。

# Creating a dictionary
dict_of_columns = dict(zip(df.key, df.value))
print(dict_of_columns)
    {'12010A': 20, '22010B': 2, '22011B': 8, '32010A': 3}

现在,我们正在创建“新年”列,该列是通过将每年加1并创建对应的键“ new_value”并创建新键而获得的。

df['next_year']=df['year'] + 1
df['new_value'] = df[['id','next_year','type']].astype(str).sum(axis=1)
print(df)
       id  year type  value     key  next_year new_value
    0   1  2010    A     20  12010A       2011    12011A
    1   2  2010    B      2  22010B       2011    22011B
    2   2  2011    B      8  22011B       2012    22012B
    3   3  2010    A      3  32010A       2011    32011A

最后,将新键-new_value映射到我们创建的字典,并删除创建的列。

df['new_value'] = df['new_value'].map(dict_of_columns).fillna(0)
df = df.drop(['key','next_year'],axis=1)
print(df)
       id  year type  value  new_value
    0   1  2010    A     20        0.0
    1   2  2010    B      2        8.0
    2   2  2011    B      8        0.0
    3   3  2010    A      3        0.0