pandas dataframe-替换行值

时间:2016-06-21 00:07:15

标签: python pandas

我有一个包含四列的数据框(请参阅下面的输入数据框)。我需要检查Meta列是否具有模式关系(例如M_relation),然后将关系列中的数字添加到元列值。如何在熊猫中做到这一点?

输入数据帧:

--------------------------------------

    Entry1 | Relation | Entry2 | Meta |

--------------------------------------

E11 | R_31 | E21 | M_xxx |

E12 | R_21 | E51 | M_relation |

E33 | R_21 | E51 | M_yyy |

E44 | R_41 | E46 | M_relation |

输出:

--------------------------------------
Entry1 | Relation | Entry2 | Meta |
--------------------------------------

E11 | R_31 | E21 | M_xxx |

E12 | R_21 | E51 | M_relation_21 |

E33 | R_21 | E51 | M_yyy |

E44 | R_41 | E46 | M_relation_41 |
--------------------------------------

1 个答案:

答案 0 :(得分:1)

你可以:

pattern = df.Meta.str.split('_').str.get(1) == 'relation'
df.loc[pattern, 'Meta'] = df.loc[pattern, 'Meta'] + '_' + df.loc[pattern, 'Relation'].str.split('_').str.get(1)

得到:

  Entry1 Relation Entry2           Meta
0    E11     R_31    E21          M_xxx
1    E12     R_21    E51  M_relation_21
2    E33     R_21    E51          M_yyy
3    E44     R_51    E51  M_relation_51