Python 基于名称列创建外部ID列

Python 基于名称列创建外部ID列,python,pandas,dataframe,foreign-keys,Python,Pandas,Dataframe,Foreign Keys,我有一个简单的数据框,例如: df = pd.DataFrame({'Name': ['John Doe', 'Jane Smith', 'John Doe', 'Jane Smith','Jack Dawson','John Doe']}) df: Name 0 John Doe 1 Jane Smith 2 John Doe 3 Jane Smith 4 Jack Dawson 5 John Doe 我

我有一个简单的数据框,例如:

df = pd.DataFrame({'Name': ['John Doe', 'Jane Smith', 'John Doe', 'Jane Smith','Jack Dawson','John Doe']})
df:
        Name
    0   John Doe
    1   Jane Smith
    2   John Doe
    3   Jane Smith
    4   Jack Dawson
    5   John Doe
我想添加一列['foreign_key'],为每个唯一的名称分配一个唯一的ID(但具有相同名称的行应具有相同的'foreign_key'。因此最终输出如下所示:

df:
            Name        Foreign_Key
        0   John Doe    foreignkey1
        1   Jane Smith  foreignkey2
        2   John Doe    foreignkey1
        3   Jane Smith  foreignkey2
        4   Jack Dawson foreignkey3
        5   John Doe    foreignkey1
我正在尝试与应用的自定义函数一起使用。 因此,我的第一步是:

name_groupby = df.groupby('Name')
这就是拆分,接下来是应用和合并。文档中似乎没有类似于此示例的任何内容,我不确定从这里可以走到哪里

我开始应用的自定义函数如下所示:

def make_foreign_key(groupby_df):
    return groupby_df['Foreign_Key'] = 'foreign_key' + num

非常感谢您的帮助!

您可以将名称编入一个具有大致相同效果的分类:

In [21]: df["Name"].astype('category')
Out[21]:
0       John Doe
1     Jane Smith
2       John Doe
3     Jane Smith
4    Jack Dawson
5       John Doe
Name: Name, dtype: category
Categories (3, object): [Jack Dawson, Jane Smith, John Doe]

这可能就足够了,或者您可以将
代码作为外键拉出

In [22]: df["Name"] = df["Name"].astype('category')

In [23]: df["Name"].cat.codes
Out[23]:
0    2
1    1
2    2
3    1
4    0
5    2
dtype: int8

In [24]: df["Foreign_Key"] = c.cat.codes

In [25]: df
Out[25]:
          Name  Foreign_Key
0     John Doe            2
1   Jane Smith            1
2     John Doe            2
3   Jane Smith            1
4  Jack Dawson            0
5     John Doe            2
你可以做:

pd.merge(
    df,
    pd.DataFrame(df.Name.unique(), columns=['Name']).reset_index().rename(columns={'index': 'Foreign_Key'}),
    on='Name'
)

         Name  Foreign_Key
0    John Doe            0
1    John Doe            0
2  Jane Smith            1
3  Jane Smith            1

不久前,我遇到了同样的问题,我的解决方案如下:

import pandas as pd
import numpy as np
values = df['Name'].unique()
values = pd.Series(np.arange(len(values)), values)
df['new_column'] = df['Name'].apply(values.get)
输出:

          Name  new_column
0     John Doe           0
1   Jane Smith           1
2     John Doe           0
3   Jane Smith           1
4  Jack Dawson           2
5     John Doe           0

为什么这回答了这个问题?你最终得到的外键对于每个唯一的名字来说都不是唯一的,对吗?@titusAdam谢谢,很好的观点,我不知道我在想什么。更新为只使用category(并添加了使用
.code
拉出fk的方法)。