【问题标题】:Python - Turn all items in a Dataframe to stringsPython - 将数据框中的所有项目转换为字符串
【发布时间】:2017-07-29 08:30:16
【问题描述】:

我遵循以下过程:In Python, how do I convert all of the items in a list to floats?,因为我的 Dataframe 的每一列都是 list,但我选择将所有值更改为 strings,而不是 floats。

df = [str(i) for i in df]

但这失败了。

它只是擦除了除第一行列名之外的所有数据。

然后,尝试df = [str(i) for i in df.values] 导致将整个 Dataframe 更改为一个大列表,但这会使数据变得混乱,无法满足我的脚本的目标,即将 Dataframe 导出到我的 Oracle 表。

有没有办法将我的 Dataframe 中不是字符串的所有项目转换为字符串?

【问题讨论】:

    标签: python string pandas dataframe


    【解决方案1】:

    你可以使用applymap方法:

    df = df.applymap(str)
    

    【讨论】:

    • 这绝对完美,并修复了我的整个代码。非常感谢
    • 我不知道你的数据框有多大,但似乎 astype 快了很多。看我的回答:)。
    • 小心使用 nan 值,它会将它们变成 'nan' 字符串。
    • astype(str) 和 applymap(str) 都将列类型保留为“对象”,这会导致以后出现问题。如何永久转换成字符串?
    【解决方案2】:

    你可以用这个:

    df = df.astype(str)
    

    出于好奇,我决定看看接受的解决方案和我的解决方案在效率上是否有任何差异。

    结果如下:

    示例 df:

    df = pd.DataFrame([list(range(1000))], index=[0])
    

    测试df.astype:

    %timeit df.astype(str) 
    >> 100 loops, best of 3: 2.18 ms per loop
    

    测试df.applymap:

    %timeit df.applymap(str)
    1 loops, best of 3: 245 ms per loop
    

    看来df.astype 快了很多:)

    【讨论】:

    • 如果您想将数据帧列表转换为字符串,您会怎么做?
    • list_of_dfs = [df.astype(str) for df in list_of_dfs]
    • 这似乎将所有数据帧放入数据帧列表中,尽管它确实将它们转换为字符串,但实际上并没有将原始 dfs 转换为字符串。我必须解压它们并将它们重新分配给它们原来的 df 名称。有没有简单的方法可以做到这一点?
    • 这有效 [df_a, df_b, df_c] = [df.astype(str) for df in [df_a, df_b, df_c]],但这不是。 list_of_dfs = [df.astype(str) for df in list_of_dfs]
    • 啊,没有真正明白你的意思。很高兴你解决了!
    【解决方案3】:

    这对我有用:

    dt.applymap(lambda x: x[0] if type(x) is list else None)
    

    【讨论】:

      【解决方案4】:

      对于 pandas >= 1.0,现在有一个专用的字符串数据类型:

      您可以使用 .astype('string'):

      将您的列转换为此 pandas 字符串数据类型
      df = df.astype('string')
      

      这与使用 str 设置 pandas 'object' 数据类型不同:

      df = df.astype(str)
      

      查看数据框的信息可以看出数据类型的差异:

      df = pd.DataFrame({
          'zipcode_str': [90210, 90211] ,
          'zipcode_string': [90210, 90211],
      })
      
      df['zipcode_str'] = df['zipcode_str'].astype(str)
      df['zipcode_string'] = df['zipcode_str'].astype('string')
      
      df.info()
      
      # you can see that the first column has dtype object
      # while the second column has the new dtype string
       #   Column          Non-Null Count  Dtype 
      ---  ------          --------------  ----- 
       0   zipcode_str     2 non-null      object
       1   zipcode_string  2 non-null      string
      dtypes: object(1), string(1)
      


      来自文档:

      “字符串”扩展类型解决了 object-dtype 的几个问题 NumPy 数组:

      1) 您可能会意外地将字符串和非字符串混合存储在一个 对象 dtype 数组。 StringArray 只能存储字符串。

      2) object dtype 会破坏 dtype 特定的操作,例如 DataFrame.select_dtypes()。没有明确的方法来选择文本 虽然排除了非文本,但仍然是 object-dtype 列。

      3) 读取代码时,object dtype数组的内容不太清楚 比字符串。


      关于 pandas 1.0 的信息可以在这里找到:
      https://pandas.pydata.org/pandas-docs/version/1.0.0/whatsnew/v1.0.0.html

      【讨论】:

        猜你喜欢
        • 2022-10-21
        • 1970-01-01
        • 2017-06-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-08-17
        • 2022-11-21
        相关资源
        最近更新 更多