【问题标题】:Copying values between columns in pandas在熊猫的列之间复制值
【发布时间】:2016-04-03 14:43:00
【问题描述】:

我有一个包含Name 和name 列的数据框。

我正在这样做:

for i in range(len(df)):
    if (some condition):
        df['name'][i] = df['Name'][i]

但我收到此警告:

试图在数据帧的切片副本上设置值

而且还需要运行一段时间,和警告有关吗?

我该怎么做?

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    你可以试试loc:

    df.loc[df['name'].notnull() , 'Name'] = df['name']
    

    对SettingWithCopyWarning的解释非常好。

    一般来说:

    df.loc[some condition , 'Name'] = df['name']
    

    【讨论】:

      【解决方案2】:

      您不想使用链式分配。你应该使用.loc:

      condition = ... # something that identifies the relevant rows.
      df.loc[condition, 'Name'] = df.loc[condition, 'name']
      

      请参阅此SO post 了解更多信息。

      这是相关 Pandas 文档的链接"Why does the assignment when using chained indexing fail!"。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-08-13
        • 2020-10-17
        • 1970-01-01
        • 1970-01-01
        • 2016-01-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多