【问题标题】:Pandas, print variable in string熊猫,在字符串中打印变量
【发布时间】:2018-05-07 19:48:02
【问题描述】:

我有一个看起来像这样的数据框(新):

num  name1  name2
11    A      AB
14    Y      YX
25    L      LS
39    Z      ZT
....

我只想在打印语句中提取 num 值,这样我的输出如下所示:

The value is 11
The value is 14
The value is 25
...

我不确定执行此操作的正确格式是什么,因为以下代码只是迭代“值是”。

 for index, row in new.iterrows():
     print('The value is').format(new['num'])

【问题讨论】:

    标签: python pandas printing


    【解决方案1】:

    使用str.join 和 f-strings

    print('\n'.join(f'The value is {n}' for n in new.num))
    
    The value is 11
    The value is 14
    The value is 25
    The value is 39
    

    一个轻微的变体和更多展示如何使用print 函数...

    print(*(f'The value is {n}' for n in new.num), sep='\n')
    
    The value is 11
    The value is 14
    The value is 25
    The value is 39
    

    【讨论】:

    • 根据我的经验,引入 python3.5+ 功能似乎永远无法与 OP 一起使用...stackoverflow.com/q/50194179/4909087
    • 是的......好吧......至少非OP可以免费欣赏它(-:
    【解决方案2】:

    稍微修改你的代码

    for index, row in df.iterrows():
        print('The value is {0}'.format(row['num']))
        
    The value is 11
    The value is 14
    The value is 25
    The value is 39
    

    使用 f 字符串:

    for index, row in df.iterrows():
        print(f"The value is {row['num']}")
    

    要打印多列,使用点表示法:

    for index, row in df.iterrows():
        print(f"{row.name1} and {row.name2} have a value of {row.num}")
    
    A and AB have a value of 11
    Y and YX have a value of 14
    L and LS have a value of 25
    Z and ZT have a value of 39
    

    【讨论】:

      【解决方案3】:

      您可以直接循环通过 Series 对象(与通过 DataFrame 对象不同)。这使您可以:

      for num in new['num']:
          print('The value is ' + str(num))
      

      【讨论】:

        【解决方案4】:

        您也可以尝试以下操作:

        for val in new.num: print('This is ', val)
        

        结果:

        This is  11
        This is  14
        This is  25
        This is  39
        

        【讨论】:

          猜你喜欢
          • 2017-07-20
          • 1970-01-01
          • 1970-01-01
          • 2012-12-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-06-26
          • 2019-10-17
          相关资源
          最近更新 更多