简体   繁体   English

仅当列的 dtype 为数字时,如何使用 Pandas 删除尾随零?

[英]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.

相关问题 如何舍入/删除熊猫列中的尾随“.0”零? - How to round/remove trailing ".0" zeros in pandas column? Python Pandas 从列中的数据中删除.0 而不丢失尾随零 - Python Pandas remove .0 from data in column without losing trailing zeros 如何截断 Pandas 时间序列数据框中的列以删除前导零和尾随零? - How to truncate a column in a Pandas time series data frame so as to remove leading and trailing zeros? 如何使用 pandas 分析识别 pandas 中的数字列和分类列。 只需要 dtype 代码不需要 pandas profiling 的分析代码 - how to recognize columns numeric and categorical in pandas using pandas profiling . only need dtype code not Analysis code of pandas profiling Python Pandas Dataframe 删除浮动尾随零 - Python Pandas Dataframe Remove Float Trailing Zeros 删除 pandas 列中的前导零,但仅适用于数字 - Remove leading zeroes in pandas column but only for numeric numpy-如何删除尾随的N * 8个零 - Numpy - How to remove trailing N*8 zeros 如何删除字符串中的前导零和尾随零? Python - How to remove leading and trailing zeros in a string? Python 如果全都不为零,如何仅显示尾随小数? - How to show only trailing decimals if they are all not zeros? 从 pandas dataframe 列中删除 dtype 数据 - Remove a dtype data from pandas dataframe column
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM