【问题标题】:SettingWithCopyWarning Python changing column datatype in DataframeSettingWithCopyWarning Python 更改 Dataframe 中的列数据类型
【发布时间】:2016-06-08 17:44:20
【问题描述】:

我有以下代码:

block_table[[compared_attribute]] = block_table[[compared_attribute]].astype(int)

我想更改列的数据类型。代码正在运行,但我收到来自 Python 的警告:SettingWithCopyWarning: 试图在 DataFrame 中的切片副本上设置一个值。 尝试改用 .loc[row_indexer,col_indexer] = value

请参阅文档中的注意事项:http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy 自我[k1] = 价值[k2]

我查看了这个警告并且我正在阅读它可能正在创建数据帧的副本,而不是仅仅覆盖它,所以我尝试了以下解决方案但没有运气......

block_table.loc[[compared_attribute]] = block_table[[compared_attribute]].astype(int)




block_table.loc[:,compared_attribute] = block_table[[compared_attribute]].astype(int)

【问题讨论】:

  • 尝试使用单括号而不是双括号,让我们知道你得到了什么。
  • 谢谢,我试过了:block_table[compared_attribute] = block_table[compared_attribute].astype(int) 但它仍然给我警告......

标签: python warnings type-conversion


【解决方案1】:

应该很简单:

block_table.loc[:,compared_attribute] = block_table[compared_attribute].astype(int)

这是假设比较属性是按列,否则,在 loc 部分切换冒号和比较属性。 如果没有数据和比较属性的示例,也很难回答。

【讨论】:

    猜你喜欢
    • 2020-12-02
    • 1970-01-01
    • 2017-06-12
    • 2018-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多