首页 > 解决方案 > 根据条件处理数据框列以在没有for循环的情况下列出的优化方法?

问题描述

问题是根据从所有非空值中分割出来的条件来获取数据帧的索引,同时在获取索引后连接索引而不使用 for 循环进行迭代?

我能够做到这一点,但是在根据非空索引对 df 进行切片后使用 for 循环。我希望在不单独迭代索引的情况下完成此操作。

df=pd.DataFrame([["a",2,1],["b",np.nan,np.nan],["c",np.nan,np.nan],["d",3,4]])
list1=[]
indexes=(df.dropna().index.values).tolist()
indexes.append(df.shape[0])
for i in range(len(indexes)-1):
    list1.append(" ".join(df[0][indexes[i]:indexes[i+1]].tolist()))

# list1 becomes ['abc', 'de']

这是示例 DF:

    0   1     2
0   a   2.0  1.0
1   b   NaN  NaN
2   c   NaN  NaN
3   d   3.0  4.0
4   e   NaN  NaN

预期的输出将是一个类似的列表:[abc,de]

解释 :

第一个字符串

a: not null (start picking)
b: null
c: null

第二个字符串

d: not null (second not-null encountered concat to second string)
e:null

标签: pythonpandasdataframe

解决方案


这是一个案例cumsum

# change all(axis=1) to any(axis=1) if only one NaN in a row is enough
s = df.iloc[:,1:].notnull().all(axis=1)

df[0].groupby(s.cumsum()).apply(''.join)

输出:

1    abc
2     de
Name: 0, dtype: object

推荐阅读