PythonPandas:从列中获取唯一字符串的最佳方法

2024-05-15 11:01:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个具有不同列的数据框,如:
1) 客户移动电话号码
2) 客户家庭电话
3) 客户nextkin电话
4) 客户传真
5) 客户id

在我的输出数据框中,我希望有如下列:
1) 客户id
2) 客户电话1
3) 客户电话2
4) 客户电话3
5) 客户电话4

输入和输出电话号码之间的映射如下(但也有优先级逻辑):

cust phone 1 = cust mobile phone no    
cust phone 2 = cust home phone    
cust phone 3 = cust nextkin phone    
cust phone 4 = cust fax 

请注意,在输入数据帧中,其中任何一个都可能为空。优先级逻辑表示,如果其中一个为空,则应将下一个可用电话号码分配给该电话列。因此,如果cust phone 2为空,但cust phone 3可用,则应为cust phone 2分配值,依此类推。此外,cust phone 1到cust phone 4都应该是唯一的(无重复)

由于dataframe很大,所以不能在行中进行迭代

以下是一个示例数据框:

df = pd.DataFrame({'cust mobile no': ['1', '2', '3'],
                  'cust home phone': [np.nan, '2', 'x'],
                  'cust nextkin phone': ['1', '2', 'g'],
                  'cust fax': [np.nan, '4', '5'],
                  'cust id': ['001', '002', '003']})

  cust mobile no cust home phone cust nextkin phone cust fax cust id
0              1             NaN                  1      NaN     001
1              2               2                  2        4     002
2              3               x                  g        5     003

预期产出:

  cust id cust phone 1 cust phone 2 cust phone 3 cust phone 4
0     001            1          NaN          NaN          NaN
1     002            2            4          NaN          NaN
2     003            3            x            g            5

Tags: 数据noidhome客户npphone电话号码
1条回答
网友
1楼 · 发布于 2024-05-15 11:01:20

首先定义一个函数,该函数使用所有四列实现所需的逻辑:

from itertools import zip_longest
input_keys = ["cust mobile no", "cust home phone", "cust nextkin phone", "cust fax"]
output_keys = [f"cust phone {n}" for n in range(1, 5)]

def assign_phone_nrs(row): 
    l = [row[k] for k in input_keys if row[k] != "nan"] # get columns != 'nan'
    l = list(dict.fromkeys(l).keys())  # remove duplicates, keep order 
    output_phone_nrs = dict(zip_longest(output_keys, l, fillvalue=np.nan))  # pad with nans & put into dict
    output_phone_nrs["cust id"] = row["cust id"]   # add original id
    return pd.Series(output_phone_nrs) 

现在将其应用于输入数据帧:

>>> df.apply(assign_phone_nrs, axis=1)                                                                                                                                              
  cust phone 1 cust phone 2 cust phone 3 cust phone 4 cust id
0            1          NaN          NaN          NaN     001
1            2            4          NaN          NaN     002
2            3            x            g            5     003

相关问题 更多 >