【问题标题】:Inserting a Pandas Series into a DataFrame makes all values Nan将 Pandas 系列插入 DataFrame 会使所有值成为 Nan
【发布时间】:2017-05-12 06:42:42
【问题描述】:

正如标题所暗示的那样,我已经将两个字典转换成这样的系列,并尝试将它们插入数据框 df。

first_series = pd.Series(first_dict, name='State Names')
second_series = pd.Series(second_dict, name='City Names')
column_loc=list(df.columns.values).index("ipAddr")
df.insert(column_loc+1, 'State Names', first_series)
df.insert(column_loc+2, 'City Names', second_series)

当我运行它时,我得到了

              ipAddr State Names City Names    ...       
respID                                         ...        
10018         ***.**.**.**  NaN        NaN     ...        
10025         **.**.**.**   NaN        NaN     ...       

系列如下

10018       Bedford
10025     Vancouver
        ...    
10267        Lompoc
10280    Pikesville
Name: State Names, dtype: object
--------------------------------------------------------
10018          Ohio
10025    Washington
        ...    
10267    California
10280      Maryland
Name: City Names, dtype: object

我检查了字典和结果系列都已填充,所以我不明白为什么会发生这种情况。

谢谢。

编辑:这里有人问过类似的问题,但没有得到回答 When I insert pandas Series into dataframe, all values become NaN

【问题讨论】:

  • 你能否举一个简短的例子来说明你的 DF 和两个系列可以重现问题?
  • 10018 Bedford 10025 Vancouver ... 10267 Lompoc 10280 Pikesville Name: State Names, dtype: object 这是第一个系列,第二个系列类似10018 Ohio 10025 Washington ... 10267 California 10280 Maryland Name: City Names, dtype: object
    两者的索引都是数据框的索引。我无法发布数据框的头部(字符限制),但它是上面看到的。 (抱歉我是新手,我还不知道如何正确格式化)
  • 你的 Series 和 df 的长度一样吗?
  • df.insert(column_loc+1, 'State Names', first_series.values) 会起作用吗?
  • 系列有 808 行,而数据框有 809 行。这种差异是因为数据表的命名列占据了一行。

标签: python pandas python-3.6


【解决方案1】:

事实证明,Series 的行数比 df 少。此外,在将 Series.values 分配给 df 列时需要使用它。

【讨论】:

    猜你喜欢
    • 2020-02-01
    • 1970-01-01
    • 2023-01-19
    • 2017-09-15
    • 2015-05-10
    • 2018-11-30
    • 2020-01-23
    • 2021-10-11
    • 2021-02-20
    相关资源
    最近更新 更多