【问题标题】:Covert a column of integers and interger + strings into all integers using multiplication based on what is in the string使用基于字符串中内容的乘法将一列整数和整数+字符串转换为所有整数
【发布时间】:2022-12-29 20:50:28
【问题描述】:

如何将此列值(主要是整数和一些字符串)转换为所有整数。

该列看起来像这样,

x1
___
128455551
92571902
123125
985166
np.NaN
2241
1.50000MMM
2.5255MMM
1.2255MMMM
np.NaN
...

我希望它看起来像这样,其中带有 MMM 的行、字符被删除,数字乘以十亿 (10**9) 并转换为整数。

有 MMMM 的行,删除字符并将数字乘以万亿 (10**12) 并转换为整数。

基本上每个 M 表示 1,000。还有其他列,所以我不能删除 np.NaN

x1
___
128455551
92571902
123125
985166
np.NaN
2241
1500000000
2525500000
1225500000000
np.NaN
...

我试过这个,

df['x1'] =np.where(df.x1.astype(str).str.contains('MMM'), (df.x1.str.replace('MMM', '').astype(float) * 10**9).astype(int), df.x1)

当我只使用 2 行时它工作正常,但是当我使用整个数据帧时我得到这个错误,IntCastingNaNError: Cannot convert non-finite values (NA or inf) to integer

我如何解决它?

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    一个可能的解决方案:

    def f(x):
        if isinstance(x, str):
            ms = x.count('M')
            return int(float(x.replace('M' * ms, '')) * 10**(3 * ms))
        else:
            return x
    
    df['X1'] = df['X1'].apply(f).astype('Int64')
    

    输出:

                  X1
    0      128455551
    1       92571902
    2         123125
    3         985166
    4           <NA>
    5           2241
    6     1500000000
    7     2525500000
    8  1225500000000
    9           <NA>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-05-18
      • 2012-09-16
      • 1970-01-01
      • 2017-02-03
      • 1970-01-01
      • 1970-01-01
      • 2012-02-21
      相关资源
      最近更新 更多