[英]In pandas, convert float64 (with NaN values) to strings (with no decimals showing)
We are trying to go from我们正在尝试从go
zed = pd.DataFrame(data = {'a': [33.0, 67.0, np.nan]})
to到
pd.DataFrame(data = {'a': ['33', '67', '']})
We've tried zed['a'].astype(np.int).astype(str)
however this throws the error Cannot convert non-finite values (NA or inf) to integer
because of the NaN value.我们已经尝试过
zed['a'].astype(np.int).astype(str)
但是这会抛出错误Cannot convert non-finite values (NA or inf) to integer
because the NaN value. Is it possible to go from floats to strings with no decimals, and with NaN values replaced by empty strings?是否可以将 go 从浮点数转换为没有小数的字符串,并将 NaN 值替换为空字符串?
First idea is use Int64
for integer NaN s and then set empty string:第一个想法是将
Int64
用于integer NaN s,然后设置空字符串:
zed['a'] = zed['a'].astype('Int64').astype(str).replace('<NA>','')
print (zed)
a
0 33
1 67
2
Or for old pandas version is possible this alternative:或者对于旧的 pandas 版本,这个替代方案是可能的:
zed['a'] = zed['a'].fillna(0).astype(int).astype(str).mask(zed['a'].isna(),'')
If need missing values insted empty strings:如果需要缺失值 insted 空字符串:
zed['a'] = zed['a'].fillna(0).astype(int).astype(str).mask(zed['a'].isna())
print (zed)
a
0 33
1 67
2 NaN
Or:或者:
zed.loc[zed['a'].notna(), 'a'] = zed['a'].astype('Int64').astype(str)
zed['a'] = zed['a'].astype('Int64').astype(str).replace('<NA>', np.nan)
You can handle the trimming of the decimal at the string level:您可以在字符串级别处理小数点的修剪:
zed['b'] = zed['a'].fillna('').astype(str).str.replace(r'\..*', '', regex=True)
or:或者:
zed['b'] = zed['a'].fillna('').astype(str).str.split('.').str[0]
or:或者:
zed['b'] = zed['a'].map('{:.0f}'.format).replace('nan', '')
output: output:
a b
0 33.0 33
1 67.0 67
2 NaN
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.