Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Dataframe.str失败,因为整个列为空_Python_Python 3.x_Pandas - Fatal编程技术网

Python Dataframe.str失败,因为整个列为空

Python Dataframe.str失败,因为整个列为空,python,python-3.x,pandas,Python,Python 3.x,Pandas,我有很多列的数据框。执行时我犯了一个错误,比如 Can only use .str accessor with string values, which use np.object_ dtype in pandas 我发现这是因为我的一列在那个特殊情况下只有Nan值,而.str在代码上失败了 df1['Merchant_old']=df1['Merchant_old'].str.lower().str.strip() 我不知道如何使用isna()仅在整个列不为空时运行上述步骤。您可以在此处创

我有很多列的数据框。执行时我犯了一个错误,比如

Can only use .str accessor with string values, which use np.object_ dtype in pandas
我发现这是因为我的一列在那个特殊情况下只有Nan值,而.str在代码上失败了

df1['Merchant_old']=df1['Merchant_old'].str.lower().str.strip()

我不知道如何使用isna()仅在整个列不为空时运行上述步骤。

您可以在此处创建一个掩码,使用
isnull
all

df=pd.DataFrame({'A':['A',np.nan,'B'],'B':[np.nan,np.nan,np.nan]})

s=df.isnull().all()
df.loc[:,s[~s].index]=df.loc[:,s[~s].index].apply(lambda x : x.str.lower().str.strip())
df
     A   B
0    a NaN
1  NaN NaN
2    b NaN

我假设
df.col
的类型是
np.float
。您可以使用
str
df.col.astype(np.object..str
一起使用。这将在最终输出中保留
np.NaN
s。

我发现这是因为我的一列在特定情况下只有NaN值,并且.str在代码上失败
错误,
str
将正常工作。