【问题标题】:Select column with the most unique values from csv, python从 csv、python 中选择具有最独特值的列
【发布时间】:2021-04-12 03:45:30
【问题描述】:

我试图想出一种方法来从 csv 文件中选择一个显示最独特值的数字列。如果有多个具有相同数量的唯一值,它应该是最左边的一个。输出应该是列名或索引。

Position,Experience in Years,Salary,Starting Date,Floor,Room
Middle Management,5,5584.10,2019-02-03,12,100
Lower Management,2,3925.52,2016-04-18,12,100
Upper Management,1,7174.46,2019-01-02,10,200
Middle Management,5,5461.25,2018-02-02,14,300
Middle Management,7,7471.43,2017-09-09,17,400
Upper Management,10,12021.31,2020-01-01,11,500
Lower Management,2,2921.92,2019-08-17,11,500
Middle Management,5,5932.94,2017-11-21,15,600
Upper Management,7,10192.14,2018-08-18,18,700

所以在这里我想要“Floor”或 4 作为我的输出,因为 Floor 和 Room 具有相同数量的唯一值,但 Floor 是最左边的(我在纯 python 中需要它,我不能使用 pandas )

我把它嵌套在一大堆其他代码中,作为我需要做的一个整体,我会省略你的细节,但这些是代码中使用的元素:

new_types_list = [str, int, str, datetime.datetime, int, int] #all the datatypes of the columns
l1_listed = ['Position', 'Experience in Years', 'Salary', 'Starting Date', 'Floor', 'Room'] #the header for each column
difference = [3, 5, 9, 9, 6, 7] #is basically the amount of unique values each column has

在这里,我尝试完全按照我之前提到的去做:

another_list = [] #now i create another list
for i in new_types_list:  # this is where the error occurs, it only fills the list with the index of the first integer 3 times instead of with the individual indices
    if i== int:
        another_list.append(new_types_list.index(i))
        
integer_listi = [difference[i] for i in another_list] #and this list is the corresponding unique values from the integers

for i in difference: #now we want to find out the one that is the highest
    if i== max(integer_listi): 
        chosen_one_i = difference.index(i) #the index of the column with the most unique values is the chosen one - 

MUV_LMNC = l1_listed[chosen_one_i]
```

【问题讨论】:

    标签: pandas csv


    【解决方案1】:

    您可以使用.nunique() 获取每列中唯一的数量:

    df = pd.read_csv("your_file.csv")
    print(df.nunique())
    

    打印:

    Position               3
    Experience in Years    5
    Salary                 9
    Starting Date          9
    Floor                  7
    Room                   7
    dtype: int64
    

    然后找到最大值,使用.idxmax():

    print(df.nunique().idxmax())
    

    打印:

    Salary
    

    编辑:只选择整数列:

    print(df.loc[:, df.dtypes == np.integer].nunique().idxmax())
    

    打印:

    Floor
    

    【讨论】:

    • 但这只返回具有最多唯一值的那个,它没有指定它必须是一个整数
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-05
    • 2018-12-16
    • 1970-01-01
    • 2022-01-17
    • 2022-01-01
    • 2019-06-25
    相关资源
    最近更新 更多