[英]Get unique elements for each grouping and write to column in Pandas Python
I have a data frame like so:我有一个像这样的数据框:
Input:输入:
year ip type
2020 101 Missing
2021 101 Type 1
2022 101 Type 2
2020 102 Missing
2021 102 Missing
2020 103 Missing
2021 103 Type 2
2021 104 Type 1
2022 104 Type 2
2022 104 Type 2
How can I convert my data frame to the following:如何将我的数据框转换为以下内容:
Expected Output:预期输出:
ip type
101 Missing/Type 1/Type 2
102 Missing
103 Missing/Type 2
104 Type 1/Type 2
Where I get all unique types for each IP.我在哪里获得每个 IP 的所有唯一类型。 How can I do this in python pandas?
我怎样才能在 python pandas 中做到这一点?
In your case do drop_duplicates
before groupby.agg
在你的情况下,在
drop_duplicates
之前做groupby.agg
out = df.drop_duplicates(['ip','type']).groupby('ip')['type'].agg('/'.join).reset_index()
Out[638]:
ip type
0 101 Missing/Type1/Type2
1 102 Missing
2 103 Missing/Type2
3 104 Type1/Type2
You can try drop_duplicates
then agg
您可以尝试
drop_duplicates
然后agg
out = df.drop_duplicates(['ip', 'type']).groupby('ip', as_index=False).agg('/'.join)
print(out)
ip type
0 101 Missing/Type 1/Type 2
1 102 Missing
2 103 Missing/Type 2
3 104 Type 1/Type 2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.