熊猫:将代表数字的字符串(带有字符)转换为浮点数/整数



从每日报告中,我使用:

pd.read_csv(filepath, sep = 't')

打开如下所示的数据帧(简化格式):

finalDf2 = pd.DataFrame(dict(
Portfolio = pd.Series(['Book1', 'Book1', 'Book2', 'Book3', 'Book1','Book1']), 
Strike = pd.Series(['108','109.10', '111', '114', '108.3', '115.0']), 
Notional = pd.Series(['0', '-0.02', '35', '. 3K', '-0.05K', '0' ]))
)

通过在"名义"列下的各种条目上运行以下内容:

type(finalDf2.iloc[ , ]

我看到 0 已经是 int 类型了。
但是,非零值是字符串。我尝试使用以下方法将字符串转换为浮点数:

finalDf2['Notional'].astype(float)

但在此之前,我如何转换所有包含"K"值的单元格? 例如

3K最终应该是float或int 30
-0。 05K应该最终是float或int -50

。不幸的是,间距实际上在文件中,因此数据帧。

这是一个可能的解决方案:

def notional_to_num(x):
if isinstance(x, (int, float)):
return x
elif isinstance(x, str):
return x if 'K' not in x else float(x.replace(" ", "0")[:-1])*1e3
else:
raise
finalDf2.loc[:, 'Notional'] = finalDf2['Notional'].apply(notional_to_num)

这给出了以下输出:

Notional Portfolio  Strike
0        0     Book1     108
1    -0.02     Book1  109.10
2       35     Book2     111
3       30     Book3     114
4      -50     Book1   108.3
5        0     Book1   115.0

首先,替换空格。

In [344]: s = finalDf2['Notional'].str.replace(' ', '0')

然后,提取数字部分和"K"部分,将 K 替换为 1000。

In [345]: (s.str.extract(r'(-?[d.]+)', expand=False).astype(float) *
s.str.extract(r'([K]+)', expand=False).replace([np.nan, 'K'], [1, 1000]) )
Out[345]:
0     0.00
1    -0.02
2    35.00
3    30.00
4   -50.00
5     0.00
Name: Notional, dtype: float64

最新更新