简体   繁体   English

获取每个分组的唯一元素并写入 Pandas Python 中的列

[英]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.

相关问题 对唯一列值进行分组以获得 pandas dataframe 列中每个唯一值的平均值 - Grouping unique column values to get average of each unique value in pandas dataframe column Python pandas 按列的唯一值分组 dataframe - Python pandas grouping a dataframe by the unique value of a column 使用 python/pandas 为 A 列中的每个唯一记录获取 B 列中的唯一值 - Get unique values in column B for each unique record in column A using python/pandas Python Pandas - 过滤 pandas dataframe 以获取一列中具有最小值的行,以获取另一列中的每个唯一值 - Python Pandas - filter pandas dataframe to get rows with minimum values in one column for each unique value in another column Pandas:为每个唯一行获取一个新列 - Pandas: get a new column for each unique row 在唯一的列键上对数据进行分组并在Pandas Python中进行联接(数据透视表) - Grouping data on unique column keys and joining (pivot table) in Pandas Python 将唯一列值分组为 pandas dataframe 列中每个唯一值的总和 - Grouping unique column values to sum of each unique value in pandas dataframe column Python Pandas获得独特的列数 - Python Pandas Get Unique Count of Column 从 Python 中的 pandas 列中的每一行获取唯一字数 - Getting the unique word count from each row in a pandas column in Python Python Pandas - 将每个键和值映射到唯一的列 - Python Pandas - Map each key & value to a unique column
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM