我正在尝试将数据帧中某列的字符串转换为int。
我有一个金额列包含这样的值:
123,123
(343,344)
我正在转换这个:
123123
343344
为此,我编写了代码:
def strToInt(str2):
'''print(type(str2))'''
if type(str2) == str:
temp = str2.replace("(", "").replace(")","").replace(",","")
'''print("GOT :" + str2 + " RETURN :" + str(int(temp)))'''
if checkInt(temp):
return int(temp)
return None
def checkInt(s):
if s[0] in ('-', '+'):
return s[1:].isdigit()
return s.isdigit()
print(df['amount'])
df['amount'] = df[['amount']].apply(lambda a: strToInt(a))
print(df['amount'])
print(df.columns)
print(df['amount'])
但我得到的都是空值:我单独检查了函数strToInt,它给出了正确的输出。
但在申请后,我得到了所有的NaN值。
之前:
0 45,105
1 24,250
2 8,35,440
3 3,00,900
4 1,69,920
之后:
0 NaN
1 NaN
2 NaN
3 NaN
4 NaN
我该如何解决此问题?
您可能可以使用正则表达式来提高效率:
df = pd.DataFrame({'amount': ['123,456', '(123,456)', '-123,465', '(-123,456)']})
df = df['amount'].str.replace(r'[^-d]', '', regex=True).astype(int)
```
output:
```
0 123456
1 123456
2 -123465
3 -123456
Name: amount, dtype: int64
```
将函数传递到列df['amount']
,而不是一列DataFrame
-df[['amount']]
:
df['amount'] = df['amount'].apply(strToInt)
print (df)
amount
0 45105
1 24250
2 835440
3 300900
4 169920
来自评论的解决方案:
a = np.where(df['amount'].str.startswith('-'), -1, 1)
df['amount'] = df['amount'].str.replace(r'D', '', regex=True).astype(int).mul(a)