Copy value from one column based on the value of another column

时光怂恿深爱的人放手 提交于 2021-01-28 10:10:41

问题


I'm trying to fill values in one column from two other columns based on the values in a fourth column.

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?


回答1:


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']

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']

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')

to become the boolean values instead of the df['D']=='Other'



来源:https://stackoverflow.com/questions/29991862/copy-value-from-one-column-based-on-the-value-of-another-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!