简体   繁体   English

在 Pandas 的特定列上用值替换数据框的某些行

[英]Replace certain rows of data frame with values, on specific column, in Pandas

Make data frame:制作数据框:

df = pd.DataFrame({'A': [0, 1, 2, 3, 4], 'B': [5, 6, 7, 8, 9], 'C': ['a', 'b', 'c', 'd', 'e']})

Looks like:看起来像:

    A   B   C
0   0   5   a
1   1   6   b
2   2   7   c
3   3   8   d
4   4   9   e

Make new column:制作新专栏:

df["coolness"] = "no"

Looks like:看起来像:

    A   B   C   coolness
0   0   5   a   no
1   1   6   b   no
2   2   7   c   no
3   3   8   d   no
4   4   9   e   no

Need to replace certain rows with "yes" in the "coolness" column.需要在“coolness”列中将某些行替换为“yes”。

Tried:试过:

 df["coolness"].replace([0, 1, 3], "yes")

But doesn't work.但不起作用。 Gives:给出:

0    no
1    no
2    no
3    no
4    no

While this:虽然这样:

df.replace([0, 1, 3], "yes")

does it only on first column:仅在第一列上执行:

    A   B   C   coolness
0   yes 5   a   no
1   yes 6   b   no
2   2   7   c   no
3   yes 8   d   no
4   4   9   e   no

Do you mean:你的意思是:

df.loc[[0,1,3], 'coolness'] = 'yes'

if 0,1,3 are index then如果 0,1,3 是索引那么

    df.loc[[0,1,3], 'coolness'] = 'yes'

if 0 1 3 are values of a column A如果 0 1 3 是 A 列的值

    def app(x):
      if x["A"]==0 or x["A"]==1 or x["A"]==3:
        x['coolness']="yes"
      return x
    f=f.apply(app,axis=1)
    f

result in both the cases结果在这两种情况下

    A   B   C   coolness
0   0   5   a   yes
1   1   6   b   yes
2   2   7   c   no
3   3   8   d   yes
4   4   9   e   no

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM