[英]Copy values from one column to other columns in same row based on specific criteria in Pandas
I have a data frame
like below: 我有一个如下
data frame
:
import pandas as pd
df = pd.DataFrame({'ID':['M001','M002','M003','M004','M005'],
'X001':[0,0,1,0,0],
'X002':[0,0,1,1,0],
'X003':[0,0,1,0,1],
'X004':[1,0,1,0,0],
'X005':[1,0,1,1,0]})
print(df)
And it looks like this: 它看起来像这样:
ID X001 X002 X003 X004 X005
0 M001 0 0 0 1 1
1 M002 0 0 0 0 0
2 M003 1 1 1 1 1
3 M004 0 1 0 0 1
4 M005 0 0 1 0 0
What I want to do is to copy the value in the ID
column into the other columns based where the value is 1
as shown below. 我想做的就是将
ID
列中的值复制到其他列中,其中值是1
,如下所示。
ID X001 X002 X003 X004 X005
0 M001 0 0 0 M001 M001
1 M002 0 0 0 0 0
2 M003 M003 M003 M003 M003 M003
3 M004 0 M004 0 0 M004
4 M005 0 0 M005 0 0
What would be the easiest and fastest way to do so on a ~2000 x ~2000 data frame
? 在〜2000 x〜2000
data frame
上,最简单,最快的方法是什么?
Here is a way, replacing 1
with a null value, Transposing, using fillna
, and transposing back: 这是一种使用空值替换
1
的方法,即使用fillna
转置并向后转置:
df.T.replace(1,pd.np.nan).fillna(df['ID']).T
ID X001 X002 X003 X004 X005
0 M001 0 0 0 M001 M001
1 M002 0 0 0 0 0
2 M003 M003 M003 M003 M003 M003
3 M004 0 M004 0 0 M004
4 M005 0 0 M005 0 0
I might use where
, for example: 我可能使用
where
,例如:
In [218]: df.where(df != 1, df.ID, axis=0)
Out[218]:
ID X001 X002 X003 X004 X005
0 M001 0 0 0 M001 M001
1 M002 0 0 0 0 0
2 M003 M003 M003 M003 M003 M003
3 M004 0 M004 0 0 M004
4 M005 0 0 M005 0 0
There's an np.where equivalent of this which, like usual, is slightly faster but I find it harder to read. 有一个np.where等效项,与往常一样,速度稍快,但我觉得很难阅读。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.