【问题标题】:How to map strings in a Pandas Series如何在 Pandas 系列中映射字符串
【发布时间】:2023-03-30 03:34:02
【问题描述】:

有没有办法通过mapcharacters 获取column 中的Pandas

例如,我想像这样映射一个列info {"1": "US", "2":"DE", "3":"CA", "4":"AU ", "5":"BE"}

因此,我想要 US 和其他显示而不是数字

编辑说明:我不想爆炸列,我想保持原样,只用字符串替换数字

0   ['3']
1   ['6']
2   ['3','4']
3   ['3','4','6']
4   ['3','4']
5   ['6']
6   ['6']
7   ['5']
8   ['5']
9   ['3', '4', '1']

【问题讨论】:

    标签: python pandas dataframe data-wrangling


    【解决方案1】:

    看起来你可以做到:

    d = {"1": "US", "2":"DE", "3":"CA", "4":"AU", "5":"BE"}
    df.dropna().explode('my_col').my_col.map(d).groupby(level=0).agg(list).reindex(df.index)
    

    【讨论】:

    • 不,我不想爆炸
    • 再次对索引进行分组后,您将拥有相同的结构@A.JT ...
    • 用 NaN 检查行
    • 嗯不知道怎么处理,现在没时间:/ @yoben
    • dropna,然后爆炸,然后重新索引 ~
    【解决方案2】:

    如果您不想爆炸,请使用 apply。但请记住,在大型数据帧上,explode 方法可能比这快得多

    测试数据框

    >>> df
            test
    0     [3, 4]
    1        [6]
    2        [3]
    3  [3, 4, 6]
    

    映射字典

    >>> info =  {"1": "US", "2":"DE", "3":"CA", "4":"AU", "5":"BE"}
    

    代码

    >>> df.test.apply(lambda x: [info.get(str(i)) for i in x])
    0          [CA, AU]
    1            [None]
    2              [CA]
    3    [CA, AU, None]
    Name: test, dtype: object
    

    【讨论】:

      猜你喜欢
      • 2019-08-29
      • 2021-12-08
      • 1970-01-01
      • 2016-09-19
      • 2011-11-25
      • 2021-01-18
      • 2018-02-24
      • 2012-09-13
      • 1970-01-01
      相关资源
      最近更新 更多