且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

根据另一列的值从一列复制值

更新时间:2022-03-14 21:55:25

您可以为此使用 'boolean indexing' 而不是迭代所有行:

You can use 'boolean indexing' for this instead of iterating over all rows:

df_copy.loc[df['D']=='Test', 'A'] = df['B']
df_copy.loc[df['D']=='Other', 'A'] = df['C']

如果你知道 D 列只包含这两个值,它甚至可以更短:

If you know that column D only consists of these two values, it can even shorter:

df_copy['A'] = df['B']
df_copy.loc[df['D']=='Other', 'A'] = df['C']

如果你想用与 in 一样的操作符来测试那个子串是否在列中,你可以这样做:

If you want to have the same as the in operator to test if that substring is in the column, you can do:

df['D'].str.contains('Other')

成为布尔值而不是 df['D']=='Other'