将熊猫数据转换为数组

时间:2018-10-31 14:32:51

标签: python pandas csv data-science

熊猫初学者在这里。 我有一个使用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,宽度,高度,按行排列,各行按如下方式堆叠:

Dictionary [“ Aldkd2”] =  92 22 12 30  29 11 98 34

我想丢弃目标为0的目标。 表中有一个或多个针对单个PatientId的行。我该怎么办?

2 个答案:

答案 0 :(得分: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]]

答案 1 :(得分:0)

使用熊猫,您可以像这样将数据读入熊猫数据框:

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

此时,dataframes值参数包含表数据。您可以遍历此数据以提取并创建所需的字典。类似于:

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的新手,这可能有助于您了解正在发生的事情。