根据另一列的值从一列复制值 [英] Copy value from one column based on the value of another column
本文介绍了根据另一列的值从一列复制值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试根据第四列中的值填充其他两列中的一列中的值.
I'm trying to fill values in one column from two other columns based on the values in a fourth column.
我有一个包含四列的 Pandas 数据框:A、B、C、D
I have a pandas dataframe with four columns: A, B, C, D
df_copy = df.copy()
for i, row in df.iterrows():
if 'Test' in row.D:
df_copy.loc[i, 'A'] = row.B
elif 'Other' in row.D:
df_copy.loc[i, 'A'] = row.C
这行得通,但速度很慢.有没有更有效的方法?
This works, but is very slow. Is there a more efficient way?
推荐答案
您可以为此使用 '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'
这篇关于根据另一列的值从一列复制值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文