[英]How to remove trailing zeros using pandas only if the column's dtype is numeric?
Suppose I have a dataframe like this,假设我有一个这样的数据框,
A | B
2.000000 | "hello 1.0"
3.00000 | "mellow"
| "trello 9.0 elo"
4.0 | "cello 3.00"
How can I get the output like this,我怎样才能得到这样的输出,
A | B
2 | "hello 1.0"
3 | "mellow"
| "trello 9.0 elo"
4 | "cello 3.00"
I want to convert all columns dtypes to string;我想将所有列 dtypes 转换为字符串; however, I want to be able to remove the trailing zeros only if the column's dtype is numeric.
但是,只有当列的 dtype 是数字时,我才希望能够删除尾随零。
There was one solution where you could use lambda function but I do not exactly remember the format.有一种您可以使用 lambda 函数的解决方案,但我不太记得格式。
So far I have this,到目前为止,我有这个,
df[base_column].astype(str).str.replace(‘.0’, ‘ ‘).replace('nan', np.nan).replace('None', np.nan)
but this code converts column B also from hello 1.0 to hello 1但此代码也将 B 列从 hello 1.0 转换为 hello 1
Any help would be appreciated!任何帮助,将不胜感激!
I guess reason for .0
values are missing values, so here is possible use integer_na
:我猜
.0
值的原因是缺失值,所以这里可以使用integer_na
:
cols = df.select_dtypes(np.number).columns
df[cols] = df[cols].astype('Int64')
If need replace all numeric to strings with removed trailing .0
use:如果需要将所有数字替换为带有删除尾随
.0
字符串,请使用:
cols = df.select_dtypes(np.number).columns
df[cols] = df[cols].astype(str).replace('\.0','',regex=True).replace(['nan','None'], np.nan)
this will only make only numerics as int sparing strings这只会使数字作为 int 备用字符串
def func(row):
if type(row[0])!=str:
return (int(row[0]))
df.apply(func,axis=1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.