Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.8k views
in Technique[技术] by (71.8m points)

How to do a string replacement in Python dataframe columns with MultiIndex

I am new to Python (and to Stock Markets) and so I am trying to learn both at the same time. My problem is currently that if I download data with yfinance from a ticker like NEL.OL that I get AttributeError: 'DataFrame' object has no attribute 'NEL'. But if I plot NETE instead it works. So the Problem might be the dot in the ticker name.

import yfinance as yf
import plotly.graph_objects as go
from datetime import date
import plotly.io as pio
pio.renderers.default = "browser" 

today = date.today()

data = yf.download(tickers = "NETE NEL.OL",
        start="2020-01-01",       
        end=today.strftime("%Y-%m-%d"),
        interval = "1d",
        group_by = 'ticker',
        auto_adjust = True,
        prepost = True,
        threads = True,
        proxy = None
    )

fig = go.Figure(
    data=go.Ohlc(
        x=data.NEL.OL.index,
        open=data.NEL.OL["Open"],
        high=data.NEL.OL["High"],
        low=data.NEL.OL["Low"],
        close=data.NEL.OL["Close"]
        )
    )
fig.show()

I tried to find and replace to '.' in the columns with data.columns = data.columns.str.replace('.', '_') resulting in an Error: AttributeError: Can only use .str accessor with Index, not MultiIndex.

Workaround no 1 could be a different syntax in the plotting command, taking the "." into account. Workaraund no 2 could be a the correct search and replace syntax which I couldn't find. Are there solutions for Both?

Cheers


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Have you tried to access with []?

fig = go.Figure(
    data=go.Ohlc(
        x=data['NEL.OL'].index,
        open=data['NEL.OL']["Open"],
        high=data['NEL.OL']["High"],
        low=data['NEL.OL']["Low"],
        close=data['NEL.OL']["Close"]
        )
    )

Alternatively, you can replace dots in column name with underscores:

data.columns.set_levels(list(map(lambda x: x.replace('.', '_'), data.columns.get_level_values(0).drop_duplicates())), level=0, inplace=True)

fig = go.Figure(
    data=go.Ohlc(
        x=data.NEL_OL.index,
        open=data.NEL_OL["Open"],
        high=data.NEL_OL["High"],
        low=data.NEL_OL["Low"],
        close=data.NEL_OL["Close"]
        )
    )

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...