繁体   English   中英

根据条件熊猫将行分为2

[英]Split row into 2 based on condition pandas

我有一个如下的CSV。 当c2,c3都是一些数字时,我想复制行。 像最后一行

Initial input
C1,C2,C3
1,2,NaN
1,NaN,3
2,4,5 #both C2C3 not NaN change this row to 2 separate rows



Expected output
C1,C2,C3
1,2,NaN #nochange
1,NaN,3 #nochange
2,NaN,5 #split1
2,4,NaN #split2

这看起来很简单,但我找不到方法。

您可以使用:


print (df)
   C1   C2   C3
0   1  2.0  NaN
1   4  7.0  8.0
2   1  NaN  3.0
3   2  4.0  5.0

mask = df['C2'].notnull() & df['C3'].notnull()
df1 = df[mask]
df1 = pd.concat([df1.drop('C2',1), df1.drop('C3',1)])
df1.index = df1.index.where(df1.index.duplicated(keep='last'), df1.index + .1)
print (df1)
     C1   C2   C3
1.0   4  NaN  8.0
3.0   2  NaN  5.0
1.1   4  7.0  NaN
3.1   2  4.0  NaN

df2 = pd.concat([df[~mask], df1]).sort_index().reset_index(drop=True)
print (df2)
   C1   C2   C3
0   1  2.0  NaN
1   4  NaN  8.0
2   4  7.0  NaN
3   1  NaN  3.0
4   2  NaN  5.0
5   2  4.0  NaN

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM