Python 如何链接熊猫中的数据记录?

Python 如何链接熊猫中的数据记录?,python,pandas,dataframe,Python,Pandas,Dataframe,我有一个csv文件,可以读入熊猫数据框。数据如下: +--------+---------+------+----------------+ |姓名|地址| ID |链接到| +--------+---------+------+----------------+ |名称1 | ABC | 1233 | 1234;1235 | |名称2 | DEF | 1234 | 1233;1236;1237 | |名称3 | GHI | 1235 | 1234;1233;2589 | +-----

我有一个csv文件,可以读入熊猫数据框。数据如下:

+--------+---------+------+----------------+
|姓名|地址| ID |链接到|
+--------+---------+------+----------------+
|名称1 | ABC | 1233 | 1234;1235      |
|名称2 | DEF | 1234 | 1233;1236;1237 |
|名称3 | GHI | 1235 | 1234;1233;2589 |
+--------+---------+------+----------------+
如何对ID和链接的列之间的链接运行分析。例如,我是否应该将链接的值转换为一个列表,并对ID列进行VLOOKUP类型分析?我知道一定有一个明显的方法可以做到这一点,但我被难住了

理想情况下,最终结果应该是一个列表或字典,其中包含行的全部属性,包括其链接到的所有其他记录


或者这是我应该将数据转换为SQL数据库的问题吗?

对于唯一和非唯一情况,可以通过以下方式获得每个ID的链接到的ID字典:

def linked_ids(df):
    #set up the dictionary
    dict = {}
    #iterate through the rows
    for row in df.index:
        #separate the semi-colon delimited linked to field
        linked_to = df.ix[row,'Linked_to'].split(";")

        if df.ix[row,'ID'] not in dict.keys():
            dict[df.ix[row,'ID']] = []

            for linked_id in linked_to:
                if linked_id not in dict[df.ix[row,'ID']]:
                    dict[df.ix[row,'ID']].append(linked_id)
        else:
            for linked_id in linked_to:
                if linked_id not in dict[df.ix[row,'ID']]:
                    dict[df.ix[row,'ID']].append(linked_id)

    return dict

对于唯一和非唯一情况,可通过以下方式获得每个ID的链接到的ID字典:

def linked_ids(df):
    #set up the dictionary
    dict = {}
    #iterate through the rows
    for row in df.index:
        #separate the semi-colon delimited linked to field
        linked_to = df.ix[row,'Linked_to'].split(";")

        if df.ix[row,'ID'] not in dict.keys():
            dict[df.ix[row,'ID']] = []

            for linked_id in linked_to:
                if linked_id not in dict[df.ix[row,'ID']]:
                    dict[df.ix[row,'ID']].append(linked_id)
        else:
            for linked_id in linked_to:
                if linked_id not in dict[df.ix[row,'ID']]:
                    dict[df.ix[row,'ID']].append(linked_id)

    return dict

如果您正在使用pandas dataframe,请尝试以下方法

df.set_index('ID').Linked_To.str.split(';').to_dict()
Out[142]: 
{1233: ['1234', '1235'],
 1234: ['1233', '1236', '1237'],
 1235: ['1234', '1233', '2589']}

如果您正在使用pandas dataframe,请尝试以下方法

df.set_index('ID').Linked_To.str.split(';').to_dict()
Out[142]: 
{1233: ['1234', '1235'],
 1234: ['1233', '1236', '1237'],
 1235: ['1234', '1233', '2589']}

我不知道你是什么意思?数据由制表符分隔。ID是唯一的吗?是的,ID是唯一的,ID列下没有重复项。@OwaisArshad如果您使用的是pandas dataframe,我们可以尝试pandas的方法,我不确定您的意思是什么?数据由制表符分隔。ID是唯一的吗?是的,ID是唯一的,ID列下没有重复项。@OwaisArshad如果您正在使用pandas dataframe,我们可以尝试pandas的方法来实现此无忧伴侣:)无忧伴侣:)谢谢!这也起了作用。我将它稍微更改为:df.set_index('ID')['LINKED_to'].str.split(';')。to_dict()@OwaisArshad aha:-)谢谢!这也起了作用。我将它稍微更改为:df.set_index('ID')['LINKED_to'].str.split(';')。to_dict()@OwaisArshad aha:-)