以下几行将 pandas.Dataframe
对象中的所有列转换为数字。
columns = ['a', 'b']
dft = pd.DataFrame(data=[['1','2'], ['3','4'],['5','6']], columns=columns)
for col in columns:
dft[col] = pd.to_numeric(dft[col])
效果很好,但是 for ... in:
很难看。
我怎样才能说使用lambda
函数和/或列表理解
来让这个循环在一行中工作?
(我尝试了很多方法,但我不知道如何将 pd.to_numeric()
的结果分配给数据帧中每列的变量名称)
最佳答案
我在 github 中找到了解决方案.
print dft
print dft.dtypes
# a b c
#0 1 2 5
#1 3 4 7
#2 5 6 9
#a object
#b object
#c object
#dtype: object
dft1 = dft.apply(pd.to_numeric)
print dft1
print dft1.dtypes
# a b c
#0 1 2 5
#1 3 4 7
#2 5 6 9
#a int64
#b int64
#c int64
#dtype: object
dft[['a', 'b']] = dft[['a', 'b']].apply(pd.to_numeric)
print dft
print dft.dtypes
# a b c
#0 1 2 5
#1 3 4 7
#2 5 6 9
#a int64
#b int64
#c object
#dtype: object
下一个解决方案是使用convert_objects
,但它会引发错误(v 0.17.0):
dft.convert_objects(convert_numeric=True)
FutureWarning: convert_objects is deprecated. Use the data-type specific converters pd.to_datetime, pd.to_timedelta and pd.to_numeric.
关于Pythonize 函数应用于 pandas.Dataframe 对象中的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33947958/