Numpy.where error on pandas如果列只包含None,则将其删除

neekobn8  于 12个月前  发布在  其他
关注(0)|答案(2)|浏览(77)

我有一个pandas嵌套框架,其列包含float s、nan s或None s。我需要重新格式化列,以便将float s格式化为带有2个小数的字符串,并将nan s/None s设置为空字符串。这一直有效,直到我遇到一个列中充满了None s的情况。然后numpy.where似乎没有考虑df["B"].isnull()掩码,即使它看起来正确,当我检查其内容。因此,None被发送到round函数,该函数引发TypeError

import pandas as pd
import numpy as np

df = pd.DataFrame().from_dict(
    {"A": [0.1, 0.2423423, 0.345345, None, np.nan], "B": [None, None, None, None, None]}
)
print("1- df :\n", df)
df.iloc[3, 0] = None
print("2- df :\n", df)
print("df.dtypes : \n", df.dtypes)

print("df.isnull() : \n", df.isnull())

df["formatted_A"] = np.where(
    (df["A"].isnull()) | (df["A"].fillna(-999.9) < 0) | (df["A"].astype(str) == ""),
    "",
    df["A"].round(2).astype(str),
)
print("Formatted A- df :\n", df)
df["formatted_B"] = np.where(
    (df["B"].isnull()) | (df["B"].fillna(-999.9) < 0) | (df["B"].astype(str) == ""),
    "",
    df["B"].round(2).astype(str),
)
print("Formatted B- df :\n", df)
File "c:\....\dataframe_none_nan_test.py", line 24, in <module>
    df["B"].round(2).astype(str),  ####
  File "C:\....\lib\site-packages\pandas\core\series.py", line 2569, in round
    result = self._values.round(decimals)
TypeError: unsupported operand type(s) for *: 'NoneType' and 'float'

我希望numpy.where + pandas.isnull()掩码一起工作,这样我的列中充满了None s就被转换成了一列空字符串。

v6ylcynt

v6ylcynt1#

示例代码

对示例代码的以下更改将解决此问题。

import pandas as pd
import numpy as np

data1 = {"A": [0.1, 0.2423423, 0.345345, np.nan, np.nan], "B": [np.nan] * 5}    
df = pd.DataFrame(data1)

验证码

df["formatted_B"] = np.where(df["B"].isna(), "", df["B"].round(2).astype(str))

df

A           B   formatted_B
0   0.100000    NaN 
1   0.242342    NaN 
2   0.345345    NaN 
3   NaN         NaN 
4   NaN         NaN

所有None列都不是浮点数。所以不能对所有None列使用舍入函数。NaN是float。
如果你能让代码和问题更简洁,我将不胜感激。

tktrz96b

tktrz96b2#

谢谢Pandas金,你让我三思而后行,现在我看到了我的错误。df["B"].round(2).astype(str)是在np.where之前计算的,而不仅仅是针对np.whereTrue的索引。
当我在列中混合输入时(如列A),它确实有效,因为pandas会自动将所有None转换为np.nan,并且正如您指出的那样,round(np.nan)是支持的。谢谢你的帮助!

相关问题