【问题标题】:Convert pandas data to array将熊猫数据转换为数组
【发布时间】:2019-04-04 18:22:41
【问题描述】:

这里是熊猫初学者。 我有一个使用 Pandas 打开的 .CSV 文件。文件格式如下:-

PatientId    x    y    width    height    target
A12kxk       23   45   10       20        1
Aldkd2       92   22   12       30        1
Aldkd2       29   11   98       34        1
Alll34                 0

我想获取一个以 PatientId 为键的字典,该值将是一个二维数组,其中包含一位患者的一行的 x、y、宽度、高度,以及如下堆叠的各种行:-

字典["Aldkd2"] = 92 22 12 30 29 11 98 34

我想丢弃那些目标为 0 的。 对于单个患者 ID,表中有一行或多行。我该怎么做?

【问题讨论】:

标签: python pandas csv data-science


【解决方案1】:

希望这能解决你的问题,

dic= df.groupby('PatientId').apply(lambda x:x[['x','y','width','height']].values.tolist()).to_dict()

输出:

{'Aldkd2': [[92.0, 22.0, 12.0, 30.0], [29.0, 11.0, 98.0, 34.0]], 'Alll34': [[nan, 0.0, nan, nan]], 'A12kxk': [[23.0, 45.0, 10.0, 20.0]]}

现在你可以随心所欲,

print dic['Aldkd2']

输出:

[[92.0, 22.0, 12.0, 30.0], [29.0, 11.0, 98.0, 34.0]]

【讨论】:

    【解决方案2】:

    使用 Pandas,您可以将数据读入 Pandas Dataframe,如下所示:

    import pandas as pd
    df = pd.read_csv('data.csv')
    

    此时,dataframes value 参数包含表数据。您可以遍历此数据以提取和构造您要查找的字典。大致如下:

    patient_info_dict = {}
    for row in df.values:
        # At this point, the first value in 'row' is your dictionary key.
    
        # Check if the patient id is already a key in the dictionary
        if row[0] not in patient_info_dict:
            # Initialize an empty array
            patient_info_dict[row[0]] = []
    
            # Append the remaining data except for the key and the last value
            patient_info_dict[row[0]].append(row[1:-1])
    
        # If the patient id is already a key in the dictionary:
        else:
            # Append the remaining data except for the key and the last value
            patient_info_dict[row[0]].append(row[1:-1])
    

    如果您使用以下命令打印字典:

    print(patient_info_dict)
    

    你会得到以下输出:

    {'A12kxk': [array([23, 45, 10, 20], dtype=object)], 'Aldkd2': [array([92, 22, 12, 39], dtype=object), array([29, 11, 98, 34], dtype=object)]}
    

    另一个答案肯定更 Pythonic,而且可能更有效。但是,如果您是 Python/Pandas 的新手,这可能有助于了解究竟发生了什么。

    【讨论】:

    • 非常感谢。虽然另一个答案是我现在要使用的,但是从长远来看,知道如何使用更少的内置函数来完成任务肯定会更有用。
    猜你喜欢
    • 1970-01-01
    • 2023-03-30
    • 1970-01-01
    • 2020-09-08
    • 2021-11-28
    • 2018-05-03
    • 2020-09-04
    • 2019-12-07
    相关资源
    最近更新 更多