AttributeError: 'str' object has no attribute 'strftime' error faced - python

I am facing this problem while coding;
import pandas as pd
import matplotlib from matplotlib import dates as d
import datetime as dt
import matplotlib.pyplot as plt
import numpy as np
data = pd.read_excel(r'F:\Downloads\Book1.xlsx', index_col=0)
data.replace('NoData', np.nan, inplace= True)
data['Time'] = data.index.map(lambda x: x.strftime("%H:%M"))
Error:
AttributeError: 'str' object has no attribute 'strftime'

You can use the parse_dates argument in your read_excel() call, and this means pandas should convert the specified column to datetime objects:
import pandas as pd
import matplotlib from matplotlib import dates as d
import datetime as dt
import matplotlib.pyplot as plt
import numpy as np
data = pd.read_excel(r'F:\Downloads\Book1.xlsx', index_col=0, parse_dates=[0])
data.replace('NoData', np.nan, inplace= True)
data['Time'] = data.index.map(lambda x: x.strftime("%H:%M"))
The documentation for read_excel is here.

I think you can use the pd.to_datetime() function to get datetime as follows:
import pandas as pd
import matplotlib from matplotlib import dates as d
import datetime as dt
import matplotlib.pyplot as plt
import numpy as np
data = pd.read_excel(r'F:\Downloads\Book1.xlsx', index_col=0)
data.replace('NoData', np.nan, inplace= True)
data['Time'] = pd.to_datetime(data.index, format="%H:%M")
You can check the pandas documentation for further information here.

Related

TypeError: Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of ‘Index’

import yfinance as yf
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
ticker = [“ZIM”,“ANDE”,“ARKK” ]
stocks = yf.download(ticker, start = “2010-01-01”, end = “2023-01-01”)
ANDE
ANDE.ANDE.resample(“M”).last()

Ploting Stem plot in pandas

I have the following code:
import pandas as pd
from pandas_datareader import data as web
import datetime
df = web.DataReader('tip', 'yahoo', start= '1,1,2017', end = datetime.datetime.today())
df1 = df.resample('W-Mon').mean()
df1["Adj Close"].pct_change().plot()
This produces this plot:
To plot in stem in pandas:
df1["Adj Close"].pct_change().stem()
Is producing this error:
AttributeError: 'Series' object has no attribute 'stem'
You could use matplotlib:
import matplotlib.pyplot as plt
plt.stem(df1["Adj Close"].pct_change().index,
df1["Adj Close"].pct_change())
plt.show()
Then customise axis/title as you like.

Data frame error when trying to display head

I'm trying to display the head 10, but keep getting:
TypeError: 'DataFrame' object is not callable
import matplotlib.pyplot as plt
import matplotlib
import pandas as pd
import numpy as np
%matplotlib inline
Pop_By_County = pd.read_csv("TexasPopByCounty2021.csv")
display(Pop_By_County.head(10))
try using>>>
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
%matplotlib inline
Pop_By_County = pd.read_csv("TexasPopByCounty2021.csv")
df = pd.DataFrame(Pop_By_Country)
df.head(10)

pandas_datareader cant print date on x axis

In following plot date is not showing on x axis what do to show date time stamp
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import datetime
import pandas_datareader as web
start=datetime.datetime(2014,1,8)
end =datetime.datetime(2019,1,8)
Tesla=web.DataReader('TSLA',"iex",start,end)
Ford=web.DataReader('F',"iex",start,end)
Tesla["open"].plot(label="Tesla",title="opening Price",figsize=(16,8))
plt.legend()
plt.show()
Your dataframe index is created as dtype object or string, let's convert index to DatetimeIndex using pd.to_datetime:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import datetime
import pandas_datareader as web
start=datetime.datetime(2014,1,8)
end =datetime.datetime(2019,1,8)
Tesla=web.DataReader('TSLA',"iex",start,end)
Ford=web.DataReader('F',"iex",start,end)
#Change Telsa index to datetime dtype
Tesla.index = pd.to_datetime(Tesla.index)
#Let's do Fords too
Ford.index = pd.to_datetime(Ford.index)
Tesla["open"].plot(label="Tesla",title="opening Price",figsize=(16,8))
plt.legend()
plt.show()
Output:

matplotlib dataframe x axis date issue

import sys
import ConfigParser
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import datetime as DT
import bokeh
sys.path.extend(['..\..\myProj\SOURCE'])
fullfilepath = "../../myProj/SOURCE/" + 'myparts.txt'
ohg_df = pd.read_csv(fullfilepath, sep="\t" )
temp_df = temp_df[['as_on_date', 'ohg_qty']]
temp_df = temp_df.sort(['as_on_date'], ascending=[1])
temp_df.set_index('as_on_date')
plt.plot(temp_df.index, temp_df.ohg_qty)
plt.show()
This is my dataframe after importing.
I am trying to plot the line graph with x axis as date mentioned in the dataframe.
Can someone guide me... I am new to pandas.
dataframe picture
output pitcure
Easier:
# Set index directly
ohg_df = pd.read_csv(fullfilepath, sep="\t", index='as_on_date')
# Convert string index to dates
ohg_df.index = pd.to_datetime(ohg_df.index)
# Get a column and plot it (taking a column keeps the index)
plt.plot(ohg_df.ohg_qty)

Categories