【问题标题】:String Formatting using many pandas columns to create a new one使用许多熊猫列创建新列的字符串格式
【发布时间】:2020-07-11 16:57:52
【问题描述】:

我想在 pandas DataFrame 中创建一个新列,就像使用 python f-Strings 或格式函数一样。 这是一个例子:

df = pd.DataFrame({"str": ["a", "b", "c", "d", "e"],
                   "int": [1, 2, 3, 4, 5]})

print(df)

  str  int
0   a    1
1   b    2
2   c    3
3   d    4
4   e    5

我想获得:

  str  int concat
0   a    1   a-01
1   b    2   b-02
2   c    3   c-03
3   d    4   d-04
4   e    5   e-05

比如:

concat = f"{str}-{int:02d}"

但直接使用 pandas 列的元素。我想解决方案是使用 pandas map、apply、agg 但没有成功。

非常感谢您的帮助。

【问题讨论】:

  • df["concat"] = df["str"]+"-"+(df["int"].astype(str).str.zfill(2))

标签: python string pandas formatting


【解决方案1】:

将 lsit 理解与 f-strings 一起使用:

df['concat'] = [f"{a}-{b:02d}" for a, b in zip(df['str'], df['int'])]

或者可以使用apply:

df['concat'] = df.apply(lambda x: f"{x['str']}-{x['int']:02d}", axis=1)

或者来自 cmets 的解决方案 Series.str.zfill:

df["concat"] = df["str"] + "-" + df["int"].astype(str).str.zfill(2)

print (df)
  str  int concat
0   a    1   a-01
1   b    2   b-02
2   c    3   c-03
3   d    4   d-04
4   e    5   e-05

【讨论】:

    【解决方案2】:

    您可以使用 list comprehension 来构建 concat 列:

    import pandas as pd
    
    df = pd.DataFrame({"str": ["a", "b", "c", "d", "e"],
                       "int": [1, 2, 3, 4, 5]})
    
    df['concat'] = [f"{s}-{i:02d}" for s, i in df[['str', 'int']].values]
    
    print(df)
    

    输出

      str  int concat
    0   a    1   a-01
    1   b    2   b-02
    2   c    3   c-03
    3   d    4   d-04
    4   e    5   e-05
    

    【讨论】:

      【解决方案3】:

      我还发现数组索引可以在 DataFrame 列上工作

      df["concat"] = df.apply(lambda x: f"{x[0]}-{x[1]:02d}", axis=1)
      
      print(df)
      
        str  int concat
      0   a    1   a-01
      1   b    2   b-02
      2   c    3   c-03
      3   d    4   d-04
      4   e    5   e-05
      

      看起来很时尚

      【讨论】:

        【解决方案4】:

        你可以使用 pandas 的string concatenate 方法:

        df['concat'] = df['str'].str.cat(df['int'].astype(str),sep='-0')
        
            str int concat
        0   a   1   a-01
        1   b   2   b-02
        2   c   3   c-03
        3   d   4   d-04
        4   e   5   e-05
        

        【讨论】:

          猜你喜欢
          • 2023-01-07
          • 1970-01-01
          • 2019-02-03
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-12-01
          • 2017-09-11
          • 2023-02-09
          相关资源
          最近更新 更多