[英]Change the dataframe column values based on unique combination of other columns
I have the following data frame: 我有以下数据框:
df=pd.DataFrame([[1,11,'a'],[2,12,'b'],[1,11,'c'],[3,12,'d'],[3,7,'e'],
[2,12,'f']])
df.columns=['id','code','name']
print(df)
id code name
0 1 11 a
1 2 12 b
2 1 11 c
3 3 12 d
4 3 7 e
5 2 12 f
For the above dataframe, I want to have only one value of column 'name' for any unique combination of column id
and code
. 对于上面的数据框,我希望列'名称'只有一个值,用于列
id
和code
任何唯一组合。 For eq, the name
for rows 0 and 2 should be same. 对于eq,行0和2的
name
应该相同。 Also, the name
for rows 1 and 5 should also be same. 此外,第1行和第5行的
name
也应相同。
id code name
0 1 11 a
1 2 12 b
2 1 11 a
3 3 12 d
4 3 7 e
5 2 12 b
Please let me know how this can be done programmatically. 请让我知道如何以编程方式完成此操作。 I have two undergo this operation on more than 100000 rows.
我有两个超过100000行进行此操作。
Thanks 谢谢
Let's use groupby
, transform
, and first
: 让我们使用
groupby
, transform
和first
:
df.assign(name=df.groupby(['id','code'])['name'].transform('first'))
Output: 输出:
id code name
0 1 11 a
1 2 12 b
2 1 11 a
3 3 12 d
4 3 7 e
5 2 12 b
Or you do not need groupby
或者你不需要
groupby
A=df.sort_values(['id','code','name']).drop_duplicates(['id','code'],keep='first').index
df.loc[~df.index.isin(A),'name']=np.nan
df.sort_values(['id','code','name']).ffill().sort_index()
Out[603]:
id code name
0 1 11 a
1 2 12 b
2 1 11 a
3 3 12 d
4 3 7 e
5 2 12 b
This is another way to solve the problem using join
and drop_duplicates
. 这是使用
join
和drop_duplicates
解决问题的另一种方法。 However, I prefer @ScottBoston's solution as well 但是,我更喜欢@ ScottBoston的解决方案
cols = ['id', 'code']
df.drop('name', 1).join(df.drop_duplicates(cols).set_index(cols), on=cols)
id code name
0 1 11 a
1 2 12 b
2 1 11 a
3 3 12 d
4 3 7 e
5 2 12 b
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.