Pandas对数字的回归楠

2024-06-02 05:25:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个pandas数据帧,如示例所示:

mydf.head()

    Date        Merchant/Description Debit/Credit
0   10/05/2018  FAKE TRANSACTION 1  -£7.50
1   09/05/2018  FAKE TRANSACTION 2  -£5.79
2   09/05/2018  FAKE TRANSACTION 3  -£28.50
3   08/05/2018  FAKE TRANSACTION 4  -£3.99
4   08/05/2018  FAKE TRANSACTION 5  -£17.99

列['Debit/Credit']的数据类型为“object”;它是字符串和NaN的混合体。在

我想把字符串转换成数字。我使用pandas.to_数字为了达到这个目的:

^{pr2}$

这将把[借方/贷方]列中的所有项目转换为NaN:

mydf.head()

    Date        Merchant/Description Debit/Credit
0   10/05/2018  FAKE TRANSACTION 1   NaN
1   09/05/2018  FAKE TRANSACTION 2   NaN
2   09/05/2018  FAKE TRANSACTION 3   NaN
3   08/05/2018  FAKE TRANSACTION 4   NaN
4   08/05/2018  FAKE TRANSACTION 5   NaN

我的代码或方法有什么错误?在


Tags: 数据字符串示例pandasdatemerchant数字description
3条回答

您也可以使用regex。在

例如:

import pandas as pd
df = pd.DataFrame({"Debit/Credit": ["-£7.50", "-£5.79", "-£28.50", "-£3.99", "-£17.99"]})
df["Debit/Credit"] = df["Debit/Credit"].str.extract("(\d*\.\d+)", expand=True).apply(pd.to_numeric)
print(df)

输出:

^{pr2}$

在转换为numeric之前,需要使用空字符串^{}£

hsbcraw[cols]=hsbcraw[cols].replace('£','', regex=True).apply(pd.to_numeric, errors='coerce')

我通常是这样转换成浮动的:

df['Debit/Credit'] = df['Debit/Credit'].replace('£', '', regex = True).astype('float')

相关问题 更多 >