python - 如何扫描 pandas 行中的第一个非零值并使用数字创建新列

标签 python python-2.7 pandas dataframe

我有一个如下所示的大型数据集:

+---+--------------------------------------+---------------------------------------+--------------------------+
|   | dc(uid): interaction_single_message_ | dc(uid): interaction_single_message_1 | dc(uid): interaction_yes |
+---+--------------------------------------+---------------------------------------+--------------------------+
| 0 |                                    0 |                                     0 |                    89884 |
| 1 |                                    0 |                                    29 |                        0 |
| 2 |                                    0 |                                   239 |                      239 |
| 3 |                                  324 |                                     0 |                        0 |
| 4 |                                12021 |                                     0 |                    12021 |
+---+--------------------------------------+---------------------------------------+--------------------------+

如何逐行选择遇到的第一个数字并将其添加到同一索引处的新列中。如果连续有多个数字,它们将始终相同,这就是我要求第一个遇到的数字的原因。

理想的输出是这样的:

+---+-------+
|   | nums  |
+---+-------+
| 0 | 89884 |
| 1 |    29 |
| 2 |   239 |
| 3 |   324 |
| 4 | 12021 |
+---+-------+

我会使用 groupby.unique() 来执行此操作吗?

最佳答案

在您的示例 df 中,只要所有当前值都相同,那么以下内容就可以工作,我们使用 bool 条件来屏蔽 0 值,然后调用 mean并传递参数axis=1来计算逐行平均值:

In [24]:

df[df>0].mean(axis=1)
Out[24]:
0    89884
1       29
2      239
3      324
4    12021
dtype: float64

关于python - 如何扫描 pandas 行中的第一个非零值并使用数字创建新列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29660422/

相关文章:

python - 将带有两个参数的函数传递给 python 中的 filter()

python - 读取大型 csv 文件的随机行、python、pandas

python - Django 1.9 TemplateSyntaxError 无法解析余数 : '==' from 'game.status=='

Python argparse 以不同的方式处理参数

python - "Split"数据帧按月

python - 如何让玩家角色移动?

python-2.7 - TensorFlow tf.equal() 运算符无法按预期工作

python - 使用 for 循环限制程序的线程

python - 在行中出现某个项目后,更改数据框中的所有行。

python - Pandas - 根据其他行中的相对值计算新列