【发布时间】:2018-09-07 08:59:03
【问题描述】:
我有一个 pd DataFrame,其中整数显示为字符串:
frame = pd.DataFrame(np.random.randn(4, 3), columns=list('ABC'), index=['1', '2', '3', '4'])
frame = frame.apply(lambda x: x.astype(str))
这给了我一个数据框:
A B C
1 -0.890 0.162 0.477
2 -1.403 0.160 -0.570
3 -1.062 -0.577 -0.370
4 1.142 0.072 -1.732
如果我输入 frame.type() 我会得到对象。 现在我想将列 ['B':'C'] 转换为数字。
假设我有几十列,因此我想对它们进行切片。 所以我要做的是:
frame.loc[:,'B':'C'] = frame.loc[:,'B':'C'].apply(lambda x: pd.to_numeric(x, errors='coerce')
如果我只想更改列,比如 B,我会输入:
frame['B'] = frame['B'].apply(lambda x: pd.to_numeric(x, errors='coerce')
这会将 B 转换为 float64 但是如果我将它与 .loc 一起使用,那么在我调用 DataFrame.info() 之后什么都不会发生!
有人可以帮助我吗?当然,我可以只输入所有列,但我想获得更实用的方法
【问题讨论】:
标签: python pandas dataframe apply