【问题标题】:pandas: convert multiple columns to stringpandas:将多列转换为字符串
【发布时间】:2016-08-30 07:57:16
【问题描述】:

我有一些列 ['a', 'b', 'c', etc.]acfloat64bobject

我想将所有列转换为字符串并保留nans。

尝试使用df[['a', 'b', 'c']] == df[['a', 'b', 'c']].astype(str),但float64 列留有空白。

目前我正在与以下内容一一进行:

df['a'] = df['a'].apply(str)
df['a'] = df['a'].replace('nan', np.nan)

使用.astype(str) 然后用np.nan 替换'' 是最好的方法吗? 附带问题:.astype(str).apply(str) 之间有区别吗?

示例输入:(dtypes:a=float64,b=object,c=float64)

a, b, c, etc.
23, 'a42', 142, etc.
51, '3', 12, etc.
NaN, NaN, NaN, etc.
24, 'a1', NaN, etc.

所需的输出:(dtypes:a=object,b=object,c=object)

a, b, c, etc.
'23', 'a42', '142', etc.
'51', 'a3', '12', etc.
NaN, NaN, NaN, etc.
'24', 'a1', NaN, etc.

【问题讨论】:

  • 您可以发布示例输入和所需的输出数据集吗?
  • @Maxu 当然,我更新了问题

标签: string python-2.7 pandas


【解决方案1】:

这会为您提供列名列表

lst = list(df)

这会将所有列转换为字符串类型

df[lst] = df[lst].astype(str)

【讨论】:

    【解决方案2】:
    df = pd.DataFrame({
        'a': [23.0, 51.0, np.nan, 24.0],
        'b': ["a42", "3", np.nan, "a1"],
        'c': [142.0, 12.0, np.nan, np.nan]})
    
    for col in df:
        df[col] = [np.nan if (not isinstance(val, str) and np.isnan(val)) else 
                   (val if isinstance(val, str) else str(int(val))) 
                   for val in df[col].tolist()]
    
    >>> df
         a    b    c
    0   23  a42  142
    1   51    3   12
    2  NaN  NaN  NaN
    3   24   a1  NaN
    
    >>> df.values
    array([['23', 'a42', '142'],
           ['51', '3', '12'],
           [nan, nan, nan],
           ['24', 'a1', nan]], dtype=object)
    

    【讨论】:

    • 谢谢!这样基本上遍历每一列,如果它不是字符串并且丢失,则留下np.nan,否则将值转换为字符串(如果我是正确的)。伟大的!你也知道如何摆脱.0s 吗?
    • 由于 np.nan,列被转换为浮点数。我会添加一些东西来转换成整数。
    【解决方案3】:

    您可以对数据框的每个元素应用.astype() 函数,也可以通过以下方式选择感兴趣的列转换为字符串。

    In [41]: df1 = pd.DataFrame({
        ...:     'a': [23.0, 51.0, np.nan, 24.0],
        ...:     'b': ["a42", "3", np.nan, "a1"],
        ...:     'c': [142.0, 12.0, np.nan, np.nan]})
        ...: 
    
    In [42]: 
    
    In [42]: df1
    Out[42]: 
          a    b      c
    0  23.0  a42  142.0
    1  51.0    3   12.0
    2   NaN  NaN    NaN
    3  24.0   a1    NaN
    
    ### Shows current data type of the columns:
    In [43]: df1.dtypes
    Out[43]: 
    a    float64
    b     object
    c    float64
    dtype: object
    
    ### Applying .astype() on each element of the dataframe converts the datatype to string
    In [45]: df1.astype(str).dtypes
    Out[45]: 
    a    object
    b    object
    c    object
    dtype: object
    
    ### Or, you could select the column of interest to convert it to strings
    In [48]: df1[["a", "b", "c"]] = df1[["a","b", "c"]].astype(str)
    
    In [49]: df1.dtypes ### Datatype update
    Out[49]: 
    a    object
    b    object
    c    object
    dtype: object
    

    【讨论】:

    • 为什么 df1.astype(str).dtypes 只显示对象类型?
    【解决方案4】:

    我是这样做的。

    从特定列中获取所有值,例如'文本'。

    k = df['text'].values
    

    然后,将每个值运行到一个新声明的字符串中,例如'字符串'

    thestring = ""
    for i in range(0,len(k)):
        thestring += k[i]
    print(thestring)
    

    因此,pandas 'text' 列中的所有字符串都已放入一个字符串变量中。

    干杯, 公平的

    【讨论】:

      猜你喜欢
      • 2020-10-22
      • 2016-09-17
      • 2020-11-20
      • 2018-01-27
      • 2014-09-30
      • 1970-01-01
      • 2019-01-14
      • 2018-07-13
      • 2019-04-08
      相关资源
      最近更新 更多