无法将['']替换为DataFrame上的方法垫

运行python2.7


问题1


我想在数据框“ test”中将空字符串“”替换为“ None”:


    from numpy.random import randn

    test = pd.DataFrame(randn(3,2))

    test.iloc[0,0]=''

    test.replace('', None)

给我错误TypeError:


无法将['']替换为DataFrame上的方法垫。


什么地方出了错?


问题2:


从numpy.random导入randn


test = pd.DataFrame(randn(3,2))

# this works

test.iloc[0,1]= 'A'

test[1] = test[1].replace('A','b')

# this does not

test.iloc[0,0]=''

test.loc[0] = test[0].replace('', None)



test 

          0         1

0                   b

1  0.042052  -1.44156

2  0.462131 -0.303288

我期待着


test 

          0         1

0    None           b

1  0.042052  -1.44156

2  0.462131 -0.303288


aluckdog
浏览 200回答 2
2回答

心有法竹

没有人会被解释为缺乏论据。尝试:test.replace({'':None})问题2:test.where(test != '', None)

UYOU

只需使用非数字即可。熊猫无论如何都会将您None转换为非数字*。其次,不要忘记将结果分配给新变量或将inplace参数设置为True。test.replace('', np.NaN)自己什么也不做。import pandas as pdimport numpy as npfrom numpy.random import randntest = pd.DataFrame(randn(3,2))test.iloc[0,0]=''test = test.replace('', np.NaN)*当所有数据具有相同的数据类型时,Pandas效果最佳,效率最高。在您的情况下为numpy.float64。np.NaN也是一个numpy的浮点数。如果要None在数据框中使用,则所有内容都需要存储为object效率较低的数据类型。np.NaN可能正是您所需要的。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python