簡體   English   中英

替換方法未從 pandas dataframe 列中刪除字符串

[英]Replace method not removing string from pandas dataframe column

嗨,我有一個 pandas dataframe 列,我需要將其設置為數字。

首先,我需要從數據中刪除“M”(數百萬)。 然后我可以使用 to_numeric function。 但最終結果似乎只是一系列 NaN。 進一步研究,數字方法不起作用,因為該列仍然包含“M” - 因此替換方法不起作用。

為什么替換方法沒有刪除“M”?

#!/usr/local/bin/python3

import requests
import pandas as pd

headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:74.0) Gecko/20100101 Firefox/74.0'}

url = 'https://www.sharesoutstandinghistory.com/ivv/'
r = requests.get(url, headers=headers)
df = pd.read_html(r.content, header =0)[1]
df.columns = ['Date', 'Value']  # set column names

print(df)

df['Value'].replace('M', '', inplace=True)  # replace M

df['Value'] = pd.to_numeric(df['Value'], errors='coerce')  # set to numeric

print(df)

這是我得到的:

           Date    Value
0      1/6/2010  194.70M
1     1/11/2010  194.45M
2     1/19/2010  193.85M
3     1/21/2010  193.70M
4     1/25/2010  192.90M
...         ...      ...
1049   3/9/2020  652.75M
1050  3/16/2020  654.45M
1051  3/23/2020  627.00M
1052   4/6/2020  631.45M
1053  4/13/2020  633.05M

[1054 rows x 2 columns]
           Date  Value
0      1/6/2010    NaN
1     1/11/2010    NaN
2     1/19/2010    NaN
3     1/21/2010    NaN
4     1/25/2010    NaN
...         ...    ...
1049   3/9/2020    NaN
1050  3/16/2020    NaN
1051  3/23/2020    NaN
1052   4/6/2020    NaN
1053  4/13/2020    NaN

也許您可以嘗試另一種方法,使用此df.Value=df.Value.str[:-1]刪除 M。

它不會刪除M ,因為沒有 substring 替換所需的regex=True參數:

df['Value'] = pd.to_numeric(df['Value'].replace('M', '', regex=True) , errors='coerce')

我認為inplace不是好習慣,請檢查thisthis

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM