【问题标题】:Python Pandas: Best way to get unique strings from a columnPython Pandas:从列中获取唯一字符串的最佳方法
【发布时间】:2020-07-10 11:56:33
【问题描述】:

我有一个包含不同列的数据框,例如:
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 分配该值,依此类推。此外,客户电话 1 到客户电话 4 都应该是唯一的(没有重复)。

由于数据框很大,因此不能对行进行迭代。

这是一个示例数据框:

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

【问题讨论】:

  • 也许this 的回答会对你有所帮助。
  • 感谢链接,但我找不到链接与我的问题之间的任何关系

标签: python string pandas


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-11-25
    • 1970-01-01
    • 2019-03-21
    • 2018-10-02
    • 2023-03-06
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多