【问题标题】:to convert the datetime.time into string [duplicate]将 datetime.time 转换为字符串 [重复]
【发布时间】:2021-04-24 11:42:02
【问题描述】:

我想将包含时间的标题为“A”的整个列转换为 datetime.time 格式的字符串, 因为我收到一个错误“TypeError:float() 参数必须是字符串或数字,而不是 datetime.time”

以下是数据:

请建议对代码进行必要的更改/添加。

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()

 

【问题讨论】:

    标签: python python-3.x pandas dataframe data-science


    【解决方案1】:

    如果数据存储为数据时间,您可能需要先使用 dt.strftime() 将其转换为 HH:MM:SS

    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())
    

    使用 dt.strftime("%H:%M:%S") 会给你:

              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
    

    列如下:

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

    如果该列是日期时间格式列并且您使用 astype(str),您将获得以下信息:

                         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
    

    列为:

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

    虽然它确实将其转换为对象(基础是 str),但您可能无法以您想要的格式“%H:%M:%S”。

    【讨论】:

      【解决方案2】:

      here 尝试这个解决方案。这可能是您正在寻找的:

      df["new_col"]= df['A'].astype(str)
      

      【讨论】:

      • 不客气!希望它有所帮助:)
      猜你喜欢
      • 2012-12-27
      • 1970-01-01
      • 2019-10-27
      • 2016-09-06
      • 1970-01-01
      • 2014-07-31
      相关资源
      最近更新 更多