python - 仅填充字符串/对象

标签 python pandas

我想将 fillna 与 pandas 数据框一起使用,但仅适用于“对象”数据类型。

我相信以下方法有效,但如果不需要,我想避免使用 concat。

import pandas as pd

new_df = pd.concat([df.select_dtypes(exclude='object'),
                    df.select_dtypes('object').fillna('')], axis=1)

最佳答案

使用 np.where() :

df[:]=np.where(df.dtypes=='object',df.fillna(''),df) #this will assign to same df

创建一个新的 df:

new_df=df.copy()
new_df[:]=np.where(df.dtypes=='object',df.fillna(''),df)

关于python - 仅填充字符串/对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57257043/

相关文章:

Python 函数调用是出血范围、有状态、无法初始化参数?

python - SQLAlchemy 嵌套 CTE 查询

Python根据特定键从嵌套列表中删除重复项和原始项

python - 使用虚拟变量进行具有多个分类变量的机器学习

python - 使用 Numpy datetime64 对象索引/切片 Pandas DataFrame

python - 如何在 python 中 grep 最后一行?

python - 将 JSON 导入 pandas 数据框错误

python - 根据正值和负值对数据框列的值进行排序?

python - 使用 Pandas 将csv文件读取为字典

python - 在 pandas-python 中或制表 : how to set FIXED column width?