【发布时间】:2014-01-13 14:33:04
【问题描述】:
我有一个看起来像这样的 pandas DataFrame:
From To Val
GE VD 1000
GE VS 1600
VS VD 1500
VS GE 600
VD GE 1200
VD VS 1300
我想将“from”或“to”列中没有“GE”的每一行替换为两行,一行在“from”列中包含“GE”,另一行在“from”列中包含“GE” “到”列。
在上面的示例中,我将用以下两行替换第三行:
GE VD 1500
VS 通用电气 1500
我尝试使用“应用”,但不知道如何返回正确的数据框。例如
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
给出一个奇怪的结果:
>> 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 to
虽然我的功能看起来是正确的:
>> myfun(df.loc[5])
Val from to
5 13 GE VD
5 13 VS GE
我可以想出一种方法,将我的数据帧过滤到两个子数据帧中,一个包含需要重复的行,另一个包含需要重复的行。然后复制第一个数据帧,进行更改并将所有三个 DF 整理在一起。但它很丑。谁能提出更优雅的方式?
换句话说,应用函数是否可以返回一个 DataFrame,就像在 R 中我们使用 ddply 所做的那样?
谢谢
【问题讨论】: