![](/img/trans.png)
[英]How do I create a new Pandas Dataframe Column with data from another column
[英]Pandas : how do I create a column based on data from the same dataframe?
我有一个类似的 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
我想添加一个新列,其中包含一年后相同id
和type
,如果它存在于 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
我想不出这样做的方法(我一直在尝试应用)。 有什么建议?
您可以尝试合并:
(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
您可以使用方法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
这是另一个涉及字典的解决方案。
# 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.