首页 > 解决方案 > 无法使用简单的条件语句修改 DataFrame。但在使用静态数字时有效

问题描述

我正在尝试使用 iterrows() 函数更改熊猫 DataFrame 对象的系列。DataFrame 充满了随机浮点数。以下是两段代码的示例:

这个有效:

for index,row in other_copy.iterrows()
    other_copy.loc[index] = (other_copy.loc[index] > 30)

但是这个没有:

for index,row in other_copy.iterrows():
   top_3 = other_copy.loc[index].nlargest(3)
   minimum = min(top_3)
   other_copy.loc[index] = (other_copy.loc[index] > minimum)

第一个相应地修改了 DataFrame,True 和 False。但是,第二个给了我以下错误:

> TypeError                                 Traceback (most recent call last) <ipython-input-116-11f6c908f54a> in <module>()
      1 for index,row in other_copy.iterrows():
----> 2     top_3 = other_copy.loc[index].nlargest(3)
      3     minimum = min(top_3)
      4     other_copy.loc[index] = (other_copy.loc[index] > minimum)

/opt/conda/lib/python3.6/site-packages/pandas/core/series.py in
nlargest(self, n, keep)    2061         dtype: float64    2062        
"""
-> 2063         return algorithms.SelectNSeries(self, n=n, keep=keep).nlargest()    2064     2065     def nsmallest(self, n=5,
keep='first'):

/opt/conda/lib/python3.6/site-packages/pandas/core/algorithms.py in
nlargest(self)
    915 
    916     def nlargest(self):
--> 917         return self.compute('nlargest')
    918 
    919     def nsmallest(self):

/opt/conda/lib/python3.6/site-packages/pandas/core/algorithms.py in
compute(self, method)
    952             raise TypeError("Cannot use method '{method}' with "
    953                             "dtype {dtype}".format(method=method,
--> 954                                                    dtype=dtype))
    955 
    956         if n <= 0:

TypeError: Cannot use method 'nlargest' with dtype object

我在这里错过了一些简单的东西吗?最小变量只是一个浮点数,应该进行比较。我什至尝试使用

int(minimum)

但它仍然给我同样的错误。我也可以使用:

print(other_copy.loc[index] > minimum)

这也可以打印正确的响应。任何想法为什么会发生这种情况?对不起,如果这很简单。

标签: pythonpandasnumpy

解决方案


问题不在于minimum,它是设置的代码minimum。当你切出你的行时,它会变成一个具有 dtype 的系列object(因为你的列中有混合的 dtype,所以 dtypeobject是唯一与所有这些兼容的)

当您尝试.nlargest()在此行切片上运行时,它清楚地告诉您问题:TypeError: Cannot use method 'nlargest' with dtype object因此您应该将您的系列转换为数字。

import pandas as pd

for index,row in other_copy.iterrows():
   top_3 = pd.to_numeric(other_copy.loc[index], errors = 'coerce').nlargest(3)
   minimum = min(top_3)
   other_copy.loc[index] = (other_copy.loc[index] > minimum)

如果行中没有可以转换为数字的条目,这可能会导致另一个错误,如果您尝试进行不安全的比较(如'str'> 'float') ,它可能会失败


推荐阅读