【问题标题】:Pandas series inserted into dataframe are read as NaN插入数据帧的 Pandas 系列被读取为 NaN
【发布时间】:2018-06-14 07:57:30
【问题描述】:

我发现,在将基于相同时间段的系列添加到现有数据帧时,它会被导入为 NaN。数据框有一个字段列,但我不明白为什么这会改变任何东西。要查看我的代码的步骤,您可以查看随附的图片。希望有人能帮忙!

Illustration showing how the dataframe that the series is inserted into and how it gets read as NaN

【问题讨论】:

  • 请提供minimal reproducible example。另见How to make good reproducible pandas examples。这意味着没有链接或图片,只有文字。
  • 索引不一样。实际呢?请提供信息作为代码而不是图像
  • 感谢 jpp 的链接!由于数据非常复杂,我很难重现。 @Quickbeam2k1:你说得对,一个数据框是一个多索引,另一个只是一个系列。但是,“实际”字段根本不相关。任何覆盖它的方法,以便我可以添加系列
  • @johan,我们都有问题,只是尝试创建一些虚拟数据

标签: python pandas dataframe series


【解决方案1】:

假设字段索引列中的值对于每一行都是“实际的”,解决方案可能如下:

test.reset_index().set_index('Date').assign(m1=m1)

该解决方案有效,但可以缩短:

days = pd.to_datetime(['2018-01-31', '2018-02-28', '2018-03-31'])
df = pd.DataFrame({'Field': ['Actual']*3, 'Date': days, 'Val':[1, 2, 3]}).set_index(['Field', 'Date'])
m1 = pd.Series([0, 2, 4], index=days)

df.reset_index(level='Field').assign(m1=m1)
    Field   Val m1
Date            
2018-01-31  Actual  1   0
2018-02-28  Actual  2   2
2018-03-31  Actual  3   4

顺便说一句,那将是一个不错的 mcve

【讨论】:

    猜你喜欢
    • 2021-12-27
    • 2015-09-08
    • 2019-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多