【问题标题】:Get other columns after applying unique / distinct on one column of dataframe pandas在数据框熊猫的一列上应用唯一/不同后获取其他列
【发布时间】:2021-03-29 06:45:16
【问题描述】:

问题

我试图在数据框中获取选定的列,但是我试图获取选定列的列必须是唯一的

情景

因此,Dataframe 包含字符串中的所有值,请不要尝试关联任何查看数据的内容。 DF 看起来像这样:

A B C D E
12 Hello 1 txt num
123 Bello 2 txt doub
7 nice 1 txt num
54 duke 1 txt num
9901 - 3 char doub
63.38 - 4 char deci
8331 - 3 char doub
91 , 5 char num

我想在C 列上运行.unique() 并获取DE 列以及C 的不同/唯一值。

审判

现在,我已经实现了我想要的输出,但我确信这也可以用很少的几行来完成。作为记录,这是我的代码。 main_df 包含上表。

dependent_variables = ["D", "E"]
Dictionary = pd.DataFrame()

new_book = {}
dependent_variables_index = []

for no, col in enumerate(main_df.columns):
    print(no, col)
    if col in dependent_variables:
        dependent_variables_index.append(no)

for cid in total_categories:
    try:
        new_book[cid] = main_df[main_df["C"] == int(cid)].iloc[0, dependent_variables_index].to_dict()
    except KeyError:
        new_book[cid] = main_df[main_df["C"] == str(cid)].iloc[0, dependent_variables_index].to_dict()

for k, v in new_book.items():
    Dictionary = Dictionary.append(v, ignore_index=True)

Dictionary.index = list(new_book.keys())
Category_Dictionary = Dictionary.reset_index().rename(columns={"index": "C"})

预期输出

C D E
1 txt num
2 txt doub
3 char doub
4 char deci
5 char num

同样,我可以生成这个输出,但是我正在寻找更优化的方法来做同样的事情。

【问题讨论】:

    标签: python pandas dataframe duplicates unique


    【解决方案1】:

    是吗:

    df[['C','D','E']].drop_duplicates('C')
    

    输出:

       C     D     E
    0  1   txt   num
    1  2   txt  doub
    4  3  char  doub
    5  4  char  deci
    7  5  char   num
    

    【讨论】:

    • Dayum,就这么简单!你第二次来帮助我@Quang。我想,我需要更多地寻找数据转换的文档。
    猜你喜欢
    • 2018-05-02
    • 1970-01-01
    • 2023-02-21
    • 2017-03-03
    • 2018-02-28
    • 2022-08-17
    • 2021-02-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多