我有以下DataFrame:
In [282]: f
Out[282]:
Strike
01-02-2019 100.0
01-02-2019 105.0
01-02-2019 110.0
01-02-2019 115.0
01-02-2019 120.0
我想将每个位置的条目解析为一个方法,并填充一个新列,如下所示:
def method(i,j):
return(i,j)
for i,j in f.index, f.Strike:
f['newcol']=method(i,j)
但收到错误。我该怎么做?
答案 0 :(得分:1)
在列表理解中使用Series.items
:
df['new'] = [method(k, v) for k, v in df.Strike.items()]
使用zip
的另一种解决方案:
df['new'] = [method(k, v) for k, v in zip(df.index, df.Strike)]
或使用DataFrame.apply
:
df['new'] = df.apply(lambda x: method(x.name, x.Strike), axis=1)
print (df)
Strike new
01-02-2019 100.0 (01-02-2019, 100.0)
01-02-2019 105.0 (01-02-2019, 105.0)
01-02-2019 110.0 (01-02-2019, 110.0)
01-02-2019 115.0 (01-02-2019, 115.0)
01-02-2019 120.0 (01-02-2019, 120.0)