对于DataFrame的每一行,在给定条件的情况下获取第一列的索引到新列中 - python

这是我的数据框的一部分。

data = [
    ['1245', np.nan, np.nan, 1.0, 1.0, ''],
    ['1246', np.nan, 1.0, 1.0, 1.0, ''],
    ['1247', 1.0, 1.0, 1.0, 1.0, ''],
    ['1248', 1.0, 1.0, np.nan, np.nan, ''],
    ['1249', np.nan, 1.0, np.nan, 1.0, '']
]

df = pd.DataFrame(data, columns = ['city_code', 'apr_12', 'may_12', 'jul_12', 'aug_12', 'first_index'])

对于DataFrame的每一行,在给定条件的情况下获取第一列的索引到新列中 - python

我想用第一个“ 1.0”(浮点数)的列的索引(apr_12,may_12,jun_12和aug_12)填充“ first_index”列。
例如,我想在第一行“ 2”的“ first_index”列中看到,因为这是该行的第一个“ 1.0”所在的位置。可以这样假设,也不会考虑“ city_code”列。

仅供参考:起初,NaN值是“ 0.0”(浮点数),但我认为继续使用NaN值和诸如first_valid_index()之类的函数会更容易(但我无法使其正常工作……)。如果需要的话,我将没有问题放回零。

你们对如何解决这个问题有任何想法吗?非常感谢

python大神给出的解决方案

您可以使用每一行并使用np.where查找第一个非null值索引

col_list = ['apr_12', 'may_12', 'jul_12', 'aug_12']
df['first_index'] = df[col_list].apply(lambda x: (np.where(~x.isnull())[0][0]), axis=1)
print(df)

输出:

  city_code  apr_12  may_12  jul_12  aug_12  first_index
0      1245     NaN     NaN     1.0     1.0            2
1      1246     NaN     1.0     1.0     1.0            1
2      1247     1.0     1.0     1.0     1.0            0
3      1248     1.0     1.0     NaN     NaN            0
4      1249     NaN     1.0     NaN     1.0            1

根据Stef的建议使用argmax或argmax将返回最大值和最小值的索引(nanargmin / nanargmax忽略nan),因此,如果您的df值不全为1,则它将无法给出第一个非nan索引。

在Flask中测试文件上传 - python

我在Flask集成测试中使用Flask-Testing。我有一个表单,该表单具有我要为其编写测试的徽标的文件上传,但是我不断收到错误消息:TypeError: 'str' does not support the buffer interface。我正在使用Python3。我找到的最接近的答案是this,但是它对我不起作用。这是我的许多尝…

USB设备发行 - python

我目前正在使用PyUSB。由于我不熟悉USB,所以我不知道如何执行以下操作。我已经从Python PyUSB成功连接到我的USB设备硬件。在代码中,我需要重置USB设备硬件。通过向硬件发送命令来完成。现在,在硬件重置后,我想从Python PyUSB释放当前的USB设备。然后,我想在重置后将其重新连接到USB设备硬件。请让我知道,如何释放USB设备连接和接口…

如果__name__ =='__main__',则为Python的Powershell等效项: - python

我真的很喜欢python的功能,例如:if __name__ == '__main__': #setup testing code here #or setup a call a function with parameters and human format the output #etc... 很好,因为我可以将Python脚本文件…

PyCharm中Django的文档字符串中未解决的引用 - python

我在Django的专案中使用Google Style Python Docstrings like in this Example。当我创建一个类并在文档字符串中使用属性符号时,Pycharm总是说-“未解决的引用”。class Post(models.Model): """ Class for posts. Attribute…

Sklearn将字符串类标签更改为int - python

我有一个pandas数据框,我试图将给定列中的值更改为字符串表示的整数。例如:df = index fruit quantity price 0 apple 5 0.99 1 apple 2 0.99 2 orange 4 0.89 4 banana 1 1.64 ... 10023 kiwi 10 0.92 我想看一下:df = index fruit q…