【问题标题】:How to convert integer type array (with some NaN) to string type array如何将整数类型数组(带有一些 NaN)转换为字符串类型数组
【发布时间】:2020-11-04 10:38:08
【问题描述】:

我有一个数组x,其中一个值是NaN

x = [1, 2, NaN, 3, 5]

除了NaN,所有元素都是整数。 该数组类型被视为 float64 而不是 int。

我想将类型从浮动转换为字符串。

我试过astype(str)。但这会产生小数点,例如x = [1.0, 2.0, NaN, 3.0, 5.0]

我试过astype(int).astype(str)。但是,在这种情况下,由于 NaN 元素,它不起作用。

那么,我如何将带有一些元素为 NaN 的整数数组转换为不带小数点的字符串类型?

感谢您的阅读。

import numpy as np
import pandas as pd

df = pd.DataFrame({'x' : [1,2, np.nan ,3,5]})

# df.dtypes

df['x'] = df['x'].astype(str)
# In this case, it make decimal point.

df['x'] = df['x'].astype(int).astype(str)
# It doesn't work due to NaN element.

【问题讨论】:

    标签: python python-3.x pandas numpy


    【解决方案1】:
    import numpy as np
    df1 = df.replace(np.nan, '', regex=True)
    

    这可能会有所帮助。它将用空字符串替换所有 NaN。

    【讨论】:

      【解决方案2】:

      您可以过滤掉 Nans 而不是用 '' 替换

      filtered_df = df[df['x'].notnull()]
      

      来源:Python pandas Filtering out nan from a data selection of a column of strings

      【讨论】:

        【解决方案3】:

        不用担心 nan,您可以使用它来确保它不会影响您的操作。

        df = pd.DataFrame({'x' : [1,2, np.nan ,3,5]})
        df = df.convert_dtypes()
        

        这使您可以使用 Nans,而无需 pandas 自动更改 dtype,并且它将列表中的项目保留为 ints。

        【讨论】:

          【解决方案4】:
          import pandas as pd
          import numpy as np
          ​
          df = pd.DataFrame({'x' : [1,2, np.nan ,3,5]})
          df.replace(np.nan,"nan",inplace=True)
          df = pd.DataFrame(map(str,df['x'])
          

          可能不是最优雅的解决方案,但可以完成工作。如果您有多个列,则可能需要使用 for 循环。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2022-10-13
            • 2022-12-17
            • 2021-12-22
            • 2013-05-03
            • 2016-09-27
            • 1970-01-01
            • 2019-02-09
            • 1970-01-01
            相关资源
            最近更新 更多