0

I want to convert the entire column titled 'A' comprising of time, which is in datetime.time format to string, as I am getting an error "TypeError: float() argument must be a string or a number, not datetime.time"

given below is the data:

enter image description here

Please suggest the necessary changes/additions be made in the code.

enter code here
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
load_var=pd.read_excel(r'path\filename.xlsx')
s=load_var.loc[0:11302,['A','B']] 
s1=s
ax.plot(s1[0:11302]['A'],s1[0:11302]['B'],color='orange',linewidth=1.2)
plt.xlabel("A",color='r',fontsize=14)
plt.ylabel("B",color="r",fontsize=14)
plt.title("A Vs B",color="r",fontsize=14)
plt.tick_params(axis='x',which='major',labelsize=7.5,rotation=90)
ax.xaxis.set_major_locator(ticker.MultipleLocator(2))
ax.xaxis.set_minor_locator(ticker.MultipleLocator(1))
plt.grid(True)
plt.ylabel("A",fontsize=14,color="red")
plt.title("A_Vs B",fontsize=14,color="red")
plt.tight_layout()

 
chinu
  • 25
  • 1
  • 7

2 Answers2

1

Try this solution from here . It might be what you're looking for :

df["new_col"]= df['A'].astype(str)
thehand0
  • 1,123
  • 4
  • 14
1

If the data is stored as a datatime, you may want to convert it into HH:MM:SS first using dt.strftime()

import pandas as pd
from datetime import datetime

df = pd.DataFrame({'A':pd.date_range('2017-01-01', freq='10S', periods=6)
                  ,'B':range(1,7)})

print (df)
print (df.info())
#df['A'] = df['A'].astype(str)
df['A'] = pd.to_datetime(df['A']).dt.strftime("%H:%M:%S")

print (df)
print (df.info())

Using dt.strftime("%H:%M:%S") will give you :

          A  B
0  00:00:00  1
1  00:00:10  2
2  00:00:20  3
3  00:00:30  4
4  00:00:40  5
5  00:00:50  6

with columns as:

 #   Column  Non-Null Count  Dtype 
---  ------  --------------  ----- 
 0   A       6 non-null      object
 1   B       6 non-null      int64 

If the column is a datetime format column and you use astype(str), you will get the following:

                     A  B
0  2017-01-01 00:00:00  1
1  2017-01-01 00:00:10  2
2  2017-01-01 00:00:20  3
3  2017-01-01 00:00:30  4
4  2017-01-01 00:00:40  5
5  2017-01-01 00:00:50  6

with columns as :

 #   Column  Non-Null Count  Dtype 
---  ------  --------------  ----- 
 0   A       6 non-null      object
 1   B       6 non-null      int64 

While it did convert it to object (underlying is str), you may not get it in the format you want "%H:%M:%S".

Joe Ferndz
  • 8,417
  • 2
  • 13
  • 33