根据条件pandas将行拆分为2

时间:2017-07-13 04:16:17

标签: python 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

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

1 个答案:

答案 0 :(得分:2)

您可以使用:

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