我有一个看起来像这样的数据框
start end 2017-06-08 2018-04-08 2019-04-20
2018-04-20 2019-04-20 NaN NaN NaN
2018-04-20 2019-04-20 NaN NaN NaN
2017-06-08 2018-04-08 NaN NaN NaN
我需要像这样
start end 2017-06-08 2018-04-20 2019-04-20
2018-04-20 2019-04-20 NaN 1 1
2018-04-20 2019-04-20 NaN 1 1
2017-06-08 2018-04-08 1 1 NaN
这意味着我将更改行值以匹配列名。
答案 0 :(得分:2)
更改行值以匹配列名
如果您要匹配开始和结束列中的列名,这是我的方法:
m=(df.stack().reset_index(level=1)
.set_index(0,append=True)['level_1'].unstack(fill_value=0).astype(bool)*1)
df.update(m)
print(df)
start end 2017-06-08 2018-04-20 2018-04-08 2019-04-20
0 2018-04-20 2019-04-20 0.0 1.0 0.0 1.0
1 2018-04-20 2019-04-20 0.0 1.0 0.0 1.0
2 2017-06-08 2018-04-08 1.0 0.0 1.0 0.0
答案 1 :(得分:1)
首先比较melt
的一种方法,然后将pivot
返回
s=df.reset_index().melt(['index','start','end'])
s['value']=s.variable.between(s.start,s.end).astype(int)
yourdf=s.pivot_table(index=['index','start','end'],columns='variable',values='value',aggfunc='first').reset_index(level=[1,2])
yourdf
variable start end ... 2018-04-20 2019-04-20
index ...
0 2018-04-20 2019-04-20 ... 1 1
1 2018-04-20 2019-04-20 ... 1 1
2 2017-06-08 2018-04-08 ... 0 0
[3 rows x 6 columns]
答案 2 :(得分:1)
IIUC:
for col in df.columns[2:]:
df[col] = np.where((df.start==col)|(df.end==col),1,np.nan)
输出:
0 start end 2017-06-08 2018-04-20 2018-04-08 2019-04-20
1 2018-04-20 2019-04-20 NaN 1.0 NaN 1.0
2 2018-04-20 2019-04-20 NaN 1.0 NaN 1.0
3 2017-06-08 2018-04-08 1.0 NaN 1.0 NaN