首页 > 解决方案 > 根据列值复制行

问题描述

我有一个df可以在列类型中有 6 个不同输入的 a:3 个输入是stringword另外something3 个输入其名称,s最后是 a:

         types     Value    File   Number
0       string       Old     dat      1.0   
1         word       Old     dat      2.0
2    something       Old     dat      3.0
3   somethings       Old     dat      4.0
4        words       Old     dat      5.0

我想得到一个 我只复制在列类型中最后df没有对应的行。s并添加str(New)到列值。

输出:

         types    Value    File   Number
0       string      Old     dat      1.0
1         word      Old     dat      2.0
2    something      Old     dat      3.0        
3   somethings      Old     dat      4.0
4        words      Old     dat      5.0
5       string      New     dat      1.0

标签: pythonpandas

解决方案


您可以执行以下操作:

def insert_rows(df):
    types = df["types"].values
    unique_without_s = [t for t in types if t[-1] != 's']
    unique_with_s = [w for w in unique_without_s if f"{w}s" in types]
    diff = [w for w in unique_without_s if w not in unique_with_s]
    new_df = df.copy()
    for _, row in df.iterrows():
        if row.types in diff:
            new_df = new_df.append({"types": row['types'], "Value": 'New', 
                           "File": row['File'], "Number": row['Number']}, ignore_index=True)
    return new_df

推荐阅读