如何在 Pandas 数据框中将整数映射为字符串值

3

我有这个Python字典:

dictionary = {
        '1':'A',
        '2':'B',
        '3':'C',
        '4':'D',
        '5':'E',
        '6':'F',
        '7':'G',
        '8':'H',
        '8':'I',
        '9':'J',
        '0':'L'
        }

我已创建了这个简单的pandas数据框:
import pandas as pd
ds = {'col1' : [12345,67890], 'col2' : [12364,78910]}

df = pd.DataFrame(data=ds)
print(df)

它长这样:

    col1   col2
0  12345  12364
1  67890  78910

我希望将col1中的每个数字(它是一个int字段)转换为上述字典中指定的对应字母。因此,基本上我希望生成的数据框如下所示:
    col1   col2 col1_transformed
0  12345  12364            ABCDE
1  67890  78910            FGHIJ

有没有一种快速、Pythonic的方法可以做到这一点呢?

2个回答

3
一种可能的解决方案(请注意,您的字典中重复了 8 -- 是否是打印错误? -- 因此我的结果与您的不匹配):
def f(x):
    return ''.join([dictionary[y] for y in str(x)])

df['col3'] = df['col1'].map(f)

输出:

    col1   col2   col3
0  12345  12364  ABCDE
1  67890  78910  FGIJL

1

尝试:

df[df.columns + "_transformed"] = df.apply(
    lambda x: [
        "".join(dictionary.get(ch, "") for ch in s) for s in map(str, x)
    ],
    axis=1,
    result_type="expand",
)
print(df)

输出:

    col1   col2 col1_transformed col2_transformed
0  12345  12364            ABCDE            ABCFD
1  67890  78910            FGIJL            GIJAL

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接