好的,我的实际问题比这个更大,但我有一个简单的可行示例。
>>> import pandas as pd
>>> import numpy as np
>>> a = pd.DataFrame(np.array([[2, 1990], [4,1991], [5,1992]]), \
... index=[1,2,3], columns=['var', 'yr'])
>>> a
var yr
1 2 1990
2 4 1991
3 5 1992
>>> b = pd.DataFrame(index=a.index, columns=['new_var'])
>>> b
new_var
1 NaN
2 NaN
3 NaN
>>> b[a.yr<1992].loc[:, 'new_var'] = a[a.yr<1992].loc[:, 'var']
>>> b
new_var
1 NaN
2 NaN
3 NaN
我希望得到以下输出:
>>> b
new_var
1 2
2 4
3 NaN
a
上进行切片是不必要的。这个就足够了b.loc[a.yr<1992, 'new_var'] = a['var']
pandas
会为您处理对齐。我给你点赞 +1。 - piRSquared