python - 根据 pandas 的条件将行分成 2 行

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

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

最佳答案

您可以使用:

<小时/>
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

关于python - 根据 pandas 的条件将行分成 2 行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45071304/

相关文章:

python - 如果它们之间的差异小于 pandas 中的固定值,则将行值替换为先前的值

python - 尝试读取多个 xlsx 文件时出现 AttributeError : 'dict' object has no attribute 'parse' .

python - 迭代 Isoweeks pandas

python - 我如何将两个不同字典中的值相乘

python - python 中的 maprdb find_by_condition 抛出异常 - 找不到类 com.mapr.db.Condition$Op

python - 在多索引 pandas 数据帧上选择范围

python - 如何使用 pandas Groupby 将不同的聚合函数应用于同一列

python - C 数组到 PyArray

python - Numpy 表 - 高级多条件选择

python - 如何连接到http ://localhost:9000/api/v1/data from jupyter in docker