I have pandas dataframe with float columns X and Y and the string column A.
The content of float columns are positive float numbers.

I am extracting the row where  column A='a' and another row where column A = 'b'
and I am doing division of float columns of 2 rows (a/b) as in code below.
The problem is that result of division is NaN. Why?
I tried to use axis=0 and axis=1 but result is the same.

我正在使用Python pandas版本1.0.5 下面是我的代码:

import pandas as pd
    ddd = {
      'A': ['a', 'b'],
      'X': [100.0, 20.0],
      'Y': [6.0, 2.0]
    }
    df = pd.DataFrame(ddd)
    df1 = df[df['A'] =='a']
    df2 = df[df['A'] == 'b']
    print(df1)
    print(df2)`

    res = df1.iloc[:, 1:].div(df2.iloc[:, 1:], axis=0)
    print(res)

    res = df1.iloc[:, 1:].div(df2.iloc[:, 1:], axis=1)
    print(res)

结果

   X    Y
 0 NaN NaN
 0 NaN NaN

推荐答案

如果索引相同,则.div将仅在两行上起作用,因此您需要使用用途:

df2 = df[df['A'] == 'b'].reset_index(drop=True)

然后,它将为保留.

     X    Y
0  5.0  3.0

Python相关问答推荐

使用numpy提取数据块

使用索引列表列表对列进行切片并获取行方向的向量长度

NP.round解算数据后NP.unique

组/群集按字符串中的子字符串或子字符串中的字符串轮询数据框

计算每个IP的平均值

在ubuntu上安装dlib时出错

不允许访问非IPM文件夹

网格基于1.Y轴与2.x轴显示在matplotlib中

找到相对于列表索引的当前最大值列表""

为什么'if x is None:pass'比'x is None'单独使用更快?

我对这个简单的异步者的例子有什么错误的理解吗?

如何将泛型类类型与函数返回类型结合使用?

read_csv分隔符正在创建无关的空列

pytest、xdist和共享生成的文件依赖项

Polars定制函数返回多列

如何在python tkinter中绑定键盘上的另一个回车?

我怎样才能让深度测试在OpenGL中使用Python和PyGame呢?

迭代工具组合不会输出大于3的序列

使用元组扩展字典的产品挑战

搜索结果未显示.我的URL选项卡显示:http://127.0.0.1:8000/search?";,而不是这个:";http://127.0.0.1:8000/search?q=name";