【问题标题】:How to convert values ( in time format) into numbers (float)如何将值(时间格式)转换为数字(浮点数)
【发布时间】:2021-09-27 04:55:00
【问题描述】:

我已经合并了数百个 excel 文件。然后我想制作一个数据透视表。但是,我发现重量列中的某些值是日期格式,导致程序无法计算。我怎样才能把它们变成数字(浮点数)?

在 excel 文件中发现问题:

代码:

li=[]
os.chdir('/content/drive/MyDrive/WEM')
allFiles=(glob.glob("*/*.xlsx"))

for file in allFiles:
  df=pd.read_excel(file,index_col=False)

  li.append(df)

WEM=pd.concat(li,axis=0,ignore_index=True)

WEM['Date']=pd.to_datetime(WEM['Start Time'],format="%d/%m/%Y %H:%M:%S")
WEM['Month']=WEM['Start Time'].dt.month

pd.pivot_table(WEM,index=['Month'],values=['weight (KG)'],aggfunc=[np.sum])

【问题讨论】:

  • 日期 1900-01-11 应该是什么浮点数?
  • 是的,如果我在 excel 中更改单元格格式,“1900-01-11”的值为 11.5。
  • 我检查了“11/01/1900”实际上是“11/01/1900 12:00:00”。当我在excel中将其更改为数值时,它是11.5。
  • Excel 本身没有日期时间类型。 Excel 中的日期实际上存储为浮点数(自 1899 年 12 月 31 日以来的天数)。如果您将该列的显示格式更改为“常规”,“日期”将消失。
  • 在对read_excel的调用中包含dtype={"weight (KG)": float}会有帮助吗?

标签: python pandas pivot-table data-conversion


【解决方案1】:

您可以过滤所有具有日期格式的行并将它们转换为如下值:

假设这个数据框:

>>> df
       weight
0          0.
1         22.
2          7.
3        20.5
4  1900-01-11  # <- should be 11.5
df['weight'] = (pd.to_datetime(df['weight'] + ' 12:00', errors='coerce') 
                - pd.to_datetime('1900-01-01')) \
                    .dt.total_seconds().div(60*60*24).add(1) \
                    .fillna(df['weight']).astype(float)

输出:

>>> df
   weight
0     0.0
1    22.0
2     7.0
3    20.5
4    11.5

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-20
    • 2013-11-11
    • 2022-01-17
    • 2023-03-20
    • 2019-01-06
    • 2018-12-23
    • 1970-01-01
    相关资源
    最近更新 更多