【问题标题】:Change all characters in a string to unicode applied to whole column pandas将字符串中的所有字符更改为应用于整列 pandas 的 unicode
【发布时间】:2020-08-02 17:57:23
【问题描述】:

我有一个字符串:

fruit1 = 'apple'

并将其更改为 unicode 代码点:

fruit 1 = int(''.join(str(ord(char)) for char in fruit1))
print(fruit1)

97112112108101

是否可以在不对每个值运行 for 循环的情况下对整个列应用相同的概念?

Sample Table:

 | Fruit |
  ------- 
 | apple |
 | berry |
 | kiwi  |

期望的输出:

| Number         |
 ----------------
| 97112112108101 |
| 98101114114121 |
| 107105119105   |

【问题讨论】:

    标签: python string pandas dataframe unicode


    【解决方案1】:

    不幸的是,mapapply 是底层循环,但在这里工作:

    df['new'] = df['Fruit'].map(lambda x:  int(''.join(str(ord(char)) for char in x)))
    #alternative
    #df['new'] = df['Fruit'].apply(lambda x:  int(''.join(str(ord(char)) for char in x)))
    print (df)
       Fruit             new
    0  apple  97112112108101
    1  berry  98101114114121
    2   kiwi    107105119105
    

    【讨论】:

      【解决方案2】:

      除了你需要它的原因(?!)之外,是的,它是可能的:

      df['Fruit'] = df['Fruit'].apply(lambda fruit1: int(''.join(str(ord(char)) for char in fruit1)))
      

      【讨论】:

        猜你喜欢
        • 2016-05-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-09-30
        • 2015-10-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多