小编use*_*381的帖子

复制一些行并更改pandas中的某些值

我有一个像这样的pandas DataFrame:

From    To    Val
GE      VD    1000
GE      VS    1600
VS      VD    1500
VS      GE     600
VD      GE    1200
VD      VS    1300
Run Code Online (Sandbox Code Playgroud)

我想将"from"或"to"列中没有"GE"的每一行替换为两行,一行在"from"列中有"GE",另一行在"to"中有"GE". "专栏.在上面的示例中,我将通过以下两行替换第三行:
GE VD 1500
VS GE 1500

我尝试使用"apply"但我无法弄清楚如何返回正确的数据框.例如

def myfun(row):
    if "GE" not in (row["from"], row["to"]):
        row1=pd.DataFrame(row).T
        row2=row1.copy()
        row1["from"]="GE"
        row2["to"]="GE"
        return pd.concat([row1, row2])
    else:
        return pd.DataFrame(row).T
Run Code Online (Sandbox Code Playgroud)

给出一个奇怪的结果:

>> df.apply(myfun, axis=1)
   Val  from  to
0  Val  from  to
1  Val  from  to
2  Val  from  to
3  Val  from  to
4  Val  from  to
5  Val  from …
Run Code Online (Sandbox Code Playgroud)

python apply pandas

5
推荐指数
2
解决办法
556
查看次数

标签 统计

apply ×1

pandas ×1

python ×1