【问题标题】:printing the pandas dataframe column following the string format按照字符串格式打印 pandas 数据框列
【发布时间】:2021-11-13 20:51:43
【问题描述】:

我有一个生成以下输出的代码

x1 = ['A', 'B', 'C', 'D']
x2 = [',', ',', ',', ',']
test_dataframe = pd.DataFrame()
test_dataframe['id'] = x1
test_dataframe['sep'] = x2
print(test_dataframe[['id','sep']].to_string(index=False))


id sep
 A   ,
 B   ,
 C   ,
 D   ,

但是,我想让 id 列的输出遵循以下格式

id  sep
 'A' ,
 'B' ,
 'C' ,
 'D' ,

如何达到这种效果。

【问题讨论】:

    标签: python-3.x pandas dataframe


    【解决方案1】:

    您可以手动将“'”添加到您的 id 列。

    df['id']= "'"+df ['id'] + "'"

    【讨论】:

      【解决方案2】:

      对于print,无法根据需要临时更改打印格式。相反,您可以将' 添加到值中,如下所示:

      x1 = ['A', 'B', 'C', 'D']
      x2 = [',', ',', ',', ',']
      test_dataframe = pd.DataFrame()
      test_dataframe['id'] = x1
      test_dataframe['sep'] = x2
      test_dataframe['id2'] = test_dataframe['id'].apply(lambda x: "'" + x + "'")
      print(test_dataframe[['id2', 'sep']].to_string(index=False))
      
      # id sep
      #'A'   ,
      #'B'   ,
      #'C'   ,
      #'D'   ,
      

      【讨论】:

        【解决方案3】:

        另一个选项是使用Series.map + str.format

        test_dataframe['id'] = test_dataframe['id'].map("'{0}'".format)
        

        输出

        >>> print(test_dataframe[['id2', 'sep']].to_string(index=False))
        
          id sep
         'A'   ,
         'B'   ,
         'C'   ,
         'D'   ,
        

        【讨论】:

        • 可以知道map函数中{0}的含义吗?谢谢。
        • @user785099 这是一个占位符,表示传递给str.format 函数的第一个位置参数。在这种情况下,表示列的每个元素。阅读更多关于它的信息here。希望对你有帮助!
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-12-25
        • 2016-06-21
        • 1970-01-01
        • 2020-08-05
        • 1970-01-01
        相关资源
        最近更新 更多