【问题标题】:Merge converting timestamp to scientific notation and losing precision合并将时间戳转换为科学记数法并丢失精度
【发布时间】:2021-10-06 17:35:48
【问题描述】:

原始时间戳 dtype int64

ts = datetime.fromtimestamp(1627741304932/1000)
print(ts)
2021-07-31 17:21:44.932000

合并数据帧后,时间戳丢失/增加 +-5 分钟,dtype 变为 float64

ts = datetime.fromtimestamp(1.627741e+12/1000)
print(ts)
2021-07-31 17:16:40

有没有办法避免这种转换或至少是精度损失?

除了丢弃一万亿以上并在合并后返回?

更新

我已经为我的问题创建了一个确切的示例:

示例

df1 = pd.DataFrame({'col1': ['ts1', 'ts2', 'ts3', 'ts4'], 
                    'col2': [1627741304932, 1627741304931, 1627741304930, 1627741304929]})
df2 = pd.DataFrame({'col1': ['ts1', 'ts2', 'ts3', 'ts5'], 
                    'col2': [1627741305932, 1627741304931, 1627741304930, 1627741304920]})

x = df1.merge(df2, on='col1', how='outer', suffixes=('_prev', '_new'))

print(x)
print(x.dtypes)

输出

这是因为在合并期间添加到数据框的 NaN 值

  col1     col2_prev      col2_new
0  ts1  1.627741e+12  1.627741e+12
1  ts2  1.627741e+12  1.627741e+12
2  ts3  1.627741e+12  1.627741e+12
3  ts4  1.627741e+12           NaN
4  ts5           NaN  1.627741e+12

col1          object
col2_prev    float64
col2_new     float64
dtype: object

我该如何解决这个问题?

【问题讨论】:

  • 只要确保两个数据框使用相同的类型即可。
  • @Mohammad 他们是,但是在他们有一些 NaN 之后,这可能是原因吗?
  • 如果两列都是整数,那么结果也应该是整数。您能否提供一个工作示例,以便我们更好地检查。
  • @Mohammad Iv'e 提供了一个例子,我发现问题确实是由 NaN 引起的

标签: python-3.x pandas dataframe merge timestamp


【解决方案1】:

所以看来问题归结为 pandas 将时间戳从 int 转换为 float。这是因为“int64”数据类型不支持 NaN 值。

为了克服这个问题,我们可以使用Nullable integer data types:

例如:

df1 = pd.DataFrame({'col1': ['ts1', 'ts2', 'ts3', 'ts4'], 
                    'col2': [1627741304932, 1627741304931, 1627741304930, 1627741304929]})
df2 = pd.DataFrame({'col1': ['ts1', 'ts2', 'ts3', 'ts5'], 
                    'col2': [1627741305932, 1627741304931, 1627741304930, 1627741304920]})
# allow NaN values (notice the capital I)
df1['col2'] =df1['col2'].astype('Int64')
df2['col2'] =df2['col2'].astype('Int64')
x = df1.merge(df2, on='col1', how='outer', suffixes=('_prev', '_new'))
print(x)
print(x.dtypes)

输出:

  col1      col2_prev       col2_new
0  ts1  1627741304932  1627741305932
1  ts2  1627741304931  1627741304931
2  ts3  1627741304930  1627741304930
3  ts4  1627741304929           <NA>
4  ts5           <NA>  1627741304920
col1         object
col2_prev     Int64
col2_new      Int64
dtype: object

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-03
    • 2017-12-24
    相关资源
    最近更新 更多