python - 检查列是否有字符串对象然后转换为数字
问题描述
我需要检查我的数据框中的列是否属于“对象”类型,然后根据该信息将该列中的所有值更改为整数。这是我为此编写的函数:
def multiply_by_scalar(self):
self.columns_to_index()
i = ask_user("What column would you like to multiply by a scalar? Please type in index:\n", int)
m = ask_user("Type in the value of the scalar:\n", int)
if self.df.columns[i] == np.object:
print("{} is of type 'object'. Scalar multiplication can only be applied to dtypes of type 'numeric'.".format(self.df.columns[i]))
c = ask_user("Would you like to convert column '{}' to type 'int'?".format(self.df.columns[i]))
if c in yes_values:
pd.to_numeric(self.df.columns[i])
self.df.columns[i] = self.df.columns[i].multiply(m)
print(self.df.columns[i])
else:
self.df.columns[i] = self.df.columns[i].multiply(m)
print(self.df.columns[i])
注意:这self.columns_to_index()
是程序中将每个列名映射到索引的函数,它不是回答问题的重要信息。
当我运行这个函数时,我得到了错误:
AttributeError: 'str' object has no attribute 'multiply
证明从字符串到整数的转换不起作用。
解决方案
这是我的解决方案:
#df.dtypes.to_dict() create a dictionary with name column as index and dtype as values
for colname, coltype in df.dtypes.to_dict().items():
if coltype == 'object' : df[colname] = df[colname].astype(int)
或者如果你有一个函数 fc 要执行
def fc(colname, coltype):
#coding fc here
for colname, coltype in df.dtypes.to_dict().items():
if coltype == 'object' : fc(colname, coltype)
推荐阅读
- java - 当我从 Git Bash 在 VS Code 中执行 pytest 时,本地 pyspark 出错
- proxy - 如何通过代理从 Gluonnlp 下载预训练模型?
- sql - 函数 plsql add 添加员工的工资
- c# - 如何在 MongoDB 中执行 IQueryable 请求?
- javascript - Cell.getValue 没有正确比较值
- reactjs - 在 React.js 项目中下载 PDF
- python - 如果一个表中的时间戳介于另一个表中的两个时间戳之间,则使用 Python Pandas 递增 1
- javascript - React-Redux 操作 - 期望 `onClick` 侦听器是一个函数,而不是获得 `object` 类型的值
- node.js - 为什么处理异步等待需要这么长时间
- reactjs - 如何在没有 fowardRef 的情况下从父级访问子级引用