python - 根据条件处理数据框列以在没有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
解决方案
这是一个案例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
推荐阅读
- c# - Swagger Codegen IO:更改服务命名约定和昵称
- flutter - Y 轴百分比仅显示两个值 0% 和 100% - Flutter Charts
- assembly - 如何在不覆盖返回地址的情况下从函数返回并将值存储在堆栈中?
- r - 德雷克计划拟合 lmer 模型失败
- python - 如何在列表中减去奇数索引值并添加偶数索引值?(a-b+c-d+e)
- javascript - 在 Laravel 应用程序上使用 npm 安装的 JS/CSS 库
- android - 如何摆脱离子页面之间的白色背景
- powershell - 如何从命令行运行 powershell 命令以使用当前目录作为参数?
- python - 即使使用 Selenium 找到元素也没有被点击
- python - pyserial 8位干净?