UPDATE:
如果需要好看字符串值,你可以做到這一點:
In [84]: df.astype(object)
Out[84]:
a b c
0 0 1 0
1 0 0 1
2 1 1 1
3 0 1 1
4 1 1 NaN
但所有值 - 都是字符串(object
在大熊貓而言):
In [85]: df.astype(object).dtypes
Out[85]:
a object
b object
c object
dtype: object
計時500K行DF:
In [86]: df = pd.concat([df] * 10**5, ignore_index=True)
In [87]: df.shape
Out[87]: (500000, 3)
In [88]: %timeit df.astype(object)
10 loops, best of 3: 113 ms per loop
In [89]: %timeit df.applymap(lambda x: int(x) if pd.notnull(x) else x).astype(object)
1 loop, best of 3: 7.86 s per loop
OLD答案:
AFAIK利用現代大熊貓的版本,你不能做到這一點。
這裏是一個演示:
In [52]: df
Out[52]:
a b c
0 1.0 NaN 0.0
1 NaN 1.0 1.0
2 0.0 0.0 NaN
In [53]: df[pd.isnull(df)] = -1
In [54]: df
Out[54]:
a b c
0 1.0 -1.0 0.0
1 -1.0 1.0 1.0
2 0.0 0.0 -1.0
In [55]: df = df.astype(int)
In [56]: df
Out[56]:
a b c
0 1 -1 0
1 -1 1 1
2 0 0 -1
我們幾乎沒有,讓我們更換-1
與NaN
:
In [57]: df[df < 0] = np.nan
In [58]: df
Out[58]:
a b c
0 1.0 NaN 0.0
1 NaN 1.0 1.0
2 0.0 0.0 NaN
另一個演示:
In [60]: df = pd.DataFrame(np.random.choice([0,1], (5,3)), columns=list('abc'))
In [61]: df
Out[61]:
a b c
0 1 0 0
1 1 0 1
2 0 1 1
3 0 0 1
4 0 0 1
外觀與c
柱發生如果我們將其中的單個單元更改爲NaN
:
In [62]: df.loc[4, 'c'] = np.nan
In [63]: df
Out[63]:
a b c
0 1 0 0.0
1 1 0 1.0
2 0 1 1.0
3 0 0 1.0
4 0 0 NaN
你想讓'NaN'的整數值是什麼?輸入'0.0,1.0,NaN'應該輸出什麼? – recursive
@recursive我希望'1.0'爲'1','0.0'爲'0','NaN'爲忽略 – ShanZhengYang