猿问

熊猫:使用另一列作为源替换值

我有一个像这样的数据框:


Source    | Description  |

Incomes   | Tax 12       |

Incomes   | Payment      |

Incomes   | Check 152    |

Incomes   | Incoming 21  |

Incomes   | Receiving    |

Payments  | Tax          |

Payments  | Incoming 7   |

Payments  | Receiving 12 |

Payments  | Check        |

Payments  | Incoming     |


首先,我替换所有包含IncomingorCheck和using的内容:IncomesCheckdf.loc


Source    | Description  |

Incomes   | Incomes      |

Incomes   | Payment      |

Incomes   | Checks       |

Incomes   | Incomes      |

Incomes   | Receiving    |

Payments  | Receiving 2  |

Payments  | Incomes      |

Payments  | Receiving 12 |

Payments  | Checks       |

Payments  | Incomes      |

现在我想用相应的值替换与列不匹配Incomes或 不匹配的所有内容,如下所示:ChecksDesciptionSource


Source    | Description  |

Incomes   | Incomes      |

Incomes   | Incomes      |

Incomes   | Checks       |

Incomes   | Incomes      |

Incomes   | Incomes      |

Payments  | Payments     |

Payments  | Incomes      |

Payments  | Payments     |

Payments  | Checks       |

Payments  | Incomes      |

我该怎么做?


我已经尝试df.loc[df['Description'].str.contains('Incomes|Checks')== False] == df['Source']过但没有成功。


提前致谢


料青山看我应如是
浏览 79回答 1
1回答

慕的地8271018

用这个,mask = df['Description'].str.contains("Incoming|Check")df.loc[~mask, "Description"] = df.loc[~mask, "Source"]df['Description'] = df['Description'].str.replace("Incoming.*", "Incomes") \    .str.replace("Check.*", "Checks")
随时随地看视频慕课网APP

相关分类

Python
我要回答