从另一个现有列的值替换列的值(如果满足条件)

时间:2019-02-28 20:47:39

标签: python-3.x pandas dataframe series

我有一个data frame,其中包含3列:

Id, Summary, Description

我要尝试的是,如果Description中的任何值与该字符串完全匹配:“这是一个空的描述”,然后将这些内容替换为Summary的内容。

例如:

之前:

   Id     Summary         Description
0  1      Cool song       This is an empty description
1  2      It was ok       was ok because needed more melody
2  3      this was sick   This is an empty description
3  4      not a fan       i prefer classical over rock
4  5      alright         This is an empty description

之后:

      Id     Summary         Description
   0  1      Cool song       Cool song
   1  2      It was ok       was ok because needed more melody
   2  3      this was sick   this was sick
   3  4      not a fan       i prefer classical over rock
   4  5      alright         alright

我使用的代码有效,但是我想知道是否有更好的方法,因为我得到警告:

输入:

 df.Description = np.where(df.Description == "This is an empty description", df.Summary, df.Description)

输出:

C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\generic.py:3643: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
  self[name] = value

1 个答案:

答案 0 :(得分:0)

Pandas中链接多个索引操作时,这是一个非常普遍的警告。您可以详细了解here。如果您想利用Pandas本机方法,则可以执行以下类似操作而不会出现任何错误。

import pandas as pd

mask = (df.Description == "This is an empty description")
df.loc[mask, 'Description'] = df.Summary