将字符串(从也包含整数的pandas dataframe列)转换为整数

时间:2017-08-10 15:47:08

标签: python pandas dataframe

我有一个pandas数据框,其中包含一个包含整数和字符串的列。

我想保留整数,并使用int.from_bytes方法仅将该列的字符串转换为整数。这可能吗?

你会建议其他任何方式吗?

我需要始终将此列中出现的任何字符串(通常最多3个字符串)转换为相同的唯一整数。谢谢。

编辑:

对迟到的回复和令人困惑的问题道歉。事实上,我确实尝试了各种不起作用的东西,但我的问题肯定不够明确。为了说明问题,首先考虑使用以下代码将字符串转换为整数:

int.from_bytes(bytearray('CD', 'ascii'), byteorder='big', signed=False)  

其中' CD'是我想要转换为整数的字符串。在这种情况下,CD'转换为int 17220.' C2'例如,将转换为17202.

就我而言,我有一个包含整数和字符串的列。字符串通常是2或3个字符串,例如上面提到的字符串。我想转换这个列,保持整数不变,并使用上面的方法将字符串转换为整数。因此,例如,列[1,' CD',2,' C2']应转换为[1,17220,2,17202]。

从@AlexanderMcFarlane的回答我找到了这样的解决方案:

import re
regex = re.compile(r"[-+]?\d+(\.0*)?$")

def is_int(v):
    return regex.match(str(v).strip()) is not None  

def string_int(x):
    if is_int(x):
        return int(float(x))
    else:
        return int.from_bytes(bytearray(x, 'ascii'), byteorder='big', signed=False)  

示例

x = [1, 'CD', 2, 'C2', '5']
df = pd.DataFrame(x, columns=['col'])

In: df
Out:     col
     0   1
     1   CD
     2   2
     3   C2
     4   5  

In: df['col']=df['col'].apply(string_int)
    df  
Out:     col
     0   1
     1   17220
     2   2
     3   17202
     4   5  

感谢您的反馈意见。非常感谢@AlexanderMcFarlane

1 个答案:

答案 0 :(得分:0)

使用这些功能

import re
regex = re.compile(r"[-+]?\d+(\.0*)?$")

def is_int(v):
    return regex.match(str(v).strip()) is not None

def safe_int(x):
    if is_int(x):
        return int(float(x))
    else:
        return x

然后操作

df[column] = df[column].apply(safe_int)

实施例

In [17]: map(safe_int, ['1.0', '1', 's', '23546.fdf'])
Out[17]: [1, 1, 's', '23546.fdf']
相关问题