使用多个数据映射规则在多个数据集中映射数据的更好方法

A better way to map data in multiple datasets, with multiple data mapping rules

我有三个数据集(final_NNppt_codeherd_id),我想在 final_NN 数据框中添加一个名为 MapValue 的新列, 并且可以从其他两个数据框中检索要添加的值,规则在代码之后的底部。

import pandas as pd

final_NN = pd.DataFrame({
    "number": [123, 456, "Unknown", "Unknown", "Unknown", "Unknown", "Unknown", "Unknown", "Unknown", "Unknown"],
    "ID": ["", "", "", "", "", "", "", "", 799, 813],
    "code": ["", "", "AA", "AA", "BB", "BB", "BB", "CC", "", ""]
})

ppt_code = pd.DataFrame({
    "code": ["AA", "AA", "BB", "BB", "CC"],
    "number": [11, 11, 22, 22, 33]
})

herd_id = pd.DataFrame({
    "ID": [799, 813],
    "number": [678, 789]
})

new_column = pd.Series([])
for i in range(len(final_NN)):
    if final_NN["number"][i] != "" and final_NN["number"][i] != "Unknown":
        new_column[i] = final_NN['number'][i]

    elif final_NN["code"][i] != "":
        for p in range(len(ppt_code)):
            if ppt_code["code"][p] == final_NN["code"][i]:
                new_column[i] = ppt_code["number"][p]

    elif final_NN["ID"][i] != "":
        for h in range(len(herd_id)):
            if herd_id["ID"][h] == final_NN["ID"][i]:
                new_column[i] = herd_id["number"][h]

    else:
        new_column[i] = ""

final_NN.insert(3, "MapValue", new_column)
print(final_NN)

final_NN:

    number   ID code
0      123          
1      456          
2  Unknown        AA
3  Unknown        AA
4  Unknown        BB
5  Unknown        BB
6  Unknown        BB
7  Unknown        CC
8  Unknown  799     
9  Unknown  813 

ppt_code:

  code  number
0   AA      11
1   AA      11
2   BB      22
3   BB      22
4   CC      33

herd_id:

    ID  number
0  799     678
1  813     789

预期输出:

    number   ID code   MapValue
0      123                  123
1      456                  456
2  Unknown        AA         11
3  Unknown        AA         11
4  Unknown        BB         22
5  Unknown        BB         22
6  Unknown        BB         22
7  Unknown        CC         33
8  Unknown  799             678
9  Unknown  813             789

规则是:

  1. 如果 final_NN 中的 number 不是 UnknownMapValue = final_NN 中的 number
  2. 如果 final_NN 中的 numberUnknownfinal_NN 中的 code 不是 Null,则搜索 ppt_code 数据框,并且使用code及其对应的“数字”映射并填写final_NN中的“MapValue”;
  3. 如果final_NN中的numbercode分别为Unknown和null,但final_NN中的ID不为Null,然后搜索herd_id dataframe,并使用ID及其对应的number填充第一个dataframe中的MapValue。如上所述,我在数据帧中应用了一个循环,这是一种实现此目的的缓慢方法。但我知道可能有更快的方法来做到这一点。只是想知道有没有人能帮助我找到一种更快速、更简单的方法来达到相同的结果?

首先从ppt_codeherd_id数据帧创建一个映射系列,然后根据规则使用Series.replace to create a new column MapNumber by replacing the Unknown values in number column with np.NaN, then use two consecutive Series.fillna along with Series.map填充MapNumber列中的缺失值:

ppt_map = ppt_code.drop_duplicates(subset=['code']).set_index('code')['number']
hrd_map = herd_id.drop_duplicates(subset=['ID']).set_index('ID')['number']

final_NN['MapNumber'] = final_NN['number'].replace({'Unknown': np.nan})
final_NN['MapNumber'] = (
    final_NN['MapNumber']
    .fillna(final_NN['code'].map(ppt_map))
    .fillna(final_NN['ID'].map(hrd_map))
)

结果:

# print(final_NN)

    number   ID code  MapNumber
0      123                123.0
1      456                456.0
2  Unknown        AA       11.0
3  Unknown        AA       11.0
4  Unknown        BB       22.0
5  Unknown        BB       22.0
6  Unknown        BB       22.0
7  Unknown        CC       33.0
8  Unknown  799           678.0
9  Unknown  813           789.0

我们简单的将三个数据框组合在一起

  1. 原来的DF删除了'Unknown'行。
  2. 'ppt_code' 更改列名称。
  3. 'pandas.concat()' 将它们连在一起。
final_NN['number'].replace('Unknown', np.NaN, inplace=True)
final_NN.dropna(inplace=True, how='any')
ppt_code.rename(columns={'code':'ID'}, inplace=True)
new_df = pd.concat([final_NN, ppt_code, herd_id], axis=0, ignore_index=True)

new_df
    number  ID  code
0   123.0       
1   456.0       
2   11.0    AA  NaN
3   11.0    AA  NaN
4   22.0    BB  NaN
5   22.0    BB  NaN
6   33.0    CC  NaN
7   678.0   799 NaN
8   789.0   813 NaN