【问题标题】:How to redirect output from print function into a pandas dataframe?如何将打印功能的输出重定向到熊猫数据框?
【发布时间】:2020-07-11 09:57:07
【问题描述】:

我有以下函数,可以通过“打印”语句为我提供输出值。但是,我希望将这些值保存在 pandas 数据框中。感谢您的帮助。

import pandas as pd

def multilabel3_message(model, scav_df):
    for ind in scav_df.index: 
        doc= (scav_df['park_data'][ind]) 
        doc_list = sentence_tokenizer(doc)
        y_pred = pipeline4.predict(doc_list)
        # Remove double class predictions
        y_pred = list(set(y_pred))
        tags = [dict_classes[i] for i in y_pred]
        # Remove `misc` tag if the list contains other tags as well.
        if len(tags) > 1 and dict_classes[46] in tags:
            del tags[tags.index(dict_classes[46])]  
        print ('{:>30} , {}'.format('['+'] ['.join(tags)+']', doc))

multilabel3_message(pipeline4, scav_df)

输出是这样的:

[T32-D] , 'True if location is a user favorite'
                       [T32-D] , 'comma separated list of URLs to images of the location'
                       [T32-D] , 'info on number of spaces in the location, localized string per Lang.'
                       [T32-D] , 'Array of integers as payment method keys accepted at location. Empty array is returned if no data is available or the location is reservable.'
                       [T32-D] , 'Array of integers as payment type keys accepted at location. Empty array is returned if no data is available or the location is reservable.'
                       [T32-D] , 'location ID for the parking location'
                       [T10-D] , 'partner ID'
               [T32-D] [T02-D] , 'type of parking (enum “1” or “2”). 1 will be the value for off-street and 2 will be value for on-street'
                       [T32-D] , 'Coordinates for the parking location'
                       [T32-D] , 'Object containing geometry information of a parking location.'
                       [T32-D] , 'Object containing geometry information of a parking location.'
                       [T32-D] , 'Full pricing details on a single type of parking for a location, time and duration.'
                       [T32-D] , 'total number of ratings for this location'
                       [T32-D] , 'name of location'
                       [T32-D] , 'address of location'

只想将此打印值保存到熊猫数据框中。

【问题讨论】:

  • 修改函数以改为返回值。

标签: python pandas numpy


【解决方案1】:

使用return代替print,并在调用函数前加上df=

【讨论】:

  • 感谢您的时间,但似乎在 for 循环之外返回值不会迭代。所以,如果我使用 return 我得到的输出为(即只有第一行) [T32-D] ,“如果位置是用户最喜欢的,则为真”。
猜你喜欢
  • 1970-01-01
  • 2017-10-02
  • 1970-01-01
  • 2014-08-09
  • 2013-02-23
  • 2011-11-01
  • 2021-10-28
  • 1970-01-01
  • 2013-09-02
相关资源
最近更新 更多