我有一个熊猫数据框架,希望使用to_gbq()将其导入bigquery。有些列具有空值,我希望保持它们的原样,而不将空值替换为nan、None或其他字符串。例如,如果我使用下面的行,如果将空值替换为0。在更改空值类型时,是否存在保留空值的方法?
df['ViewersStart']=df['ViewersStart'].fillna(0).astype('int64')
发布于 2018-10-11 13:40:22
使用loc
,只替换ViewersStart
不为空的地方:
df.loc[df.ViewersStart.notnull(),'ViewersStart'] = df.loc[df.ViewersStart.notnull(),'ViewersStart'].astype('int64')
示例
df = pd.DataFrame({'ViewersStart':['1','5',6,np.nan,'12']})
>>> df
ViewersStart
0 1
1 5
2 6
3 NaN
4 12
# Notice that your column is a mix of strings, ints and NaN
>>> df.values
array([['1'],
['5'],
[6],
[nan],
['12']], dtype=object)
df.loc[df.ViewersStart.notnull(),'ViewersStart'] = df.loc[df.ViewersStart.notnull(),'ViewersStart'].astype('int64')
>>> df
ViewersStart
0 1
1 5
2 6
3 NaN
4 12
# Notice that all non-null values are now ints
>>> df.values
array([[1],
[5],
[6],
[nan],
[12]], dtype=object)
https://stackoverflow.com/questions/52769259
复制