【问题标题】:Dynamically create string from pandas column从 pandas 列动态创建字符串
【发布时间】:2021-03-29 08:01:21
【问题描述】:

我有两个数据框,如下图,一个是df,另一个是异常:-

d = {'10028': [0], '1058': [25], '20120': [29], '20121': [22],'20122': [0], '20123': [0], '5043': [0], '5046': [0]}
    
    df = pd.DataFrame(data=d)

df 的镜像副本中的基本异常值将是 0 或 1,表示值为 1 的异常和值为 0 的非异常

d = {'10028': [0], '1058': [1], '20120': [1], '20121': [0],'20122': [0], '20123': [0], '5043': [0], '5046': [0]}

anomalies = pd.DataFrame(data=d)

我正在使用以下代码将其转换为特定格式:-

details = (
            '\n' + 'Metric Name' + '\t' + 'Count' + '\t' + 'Anomaly' +
            '\n' + '10028:' + '\t' + str(df.tail(1)['10028'][0]) + '\t' + str(anomalies['10028'][0]) + 
            '\n' + '1058:' + '\t' + '\t' + str(df.tail(1)['1058'][0]) + '\t' + str(anomalies['1058'][0]) + 
            '\n' + '20120:' + '\t' + str(df.tail(1)['20120'][0]) + '\t' + str(anomalies['20120'][0]) + 
            '\n' + '20121:' + '\t' + str(round(df.tail(1)['20121'][0], 2)) + '\t' + str(anomalies['20121'][0]) + 
            '\n' + '20122:' + '\t' + str(round(df.tail(1)['20122'][0], 2)) + '\t' + str(anomalies['20122'][0]) +
            '\n' + '20123:' + '\t' + str(round(df.tail(1)['20123'][0], 3)) + '\t' + str(anomalies['20123'][0]) +
            '\n' + '5043:' + '\t' + str(round(df.tail(1)['5043'][0], 3)) + '\t' + str(anomalies['5043'][0]) +
            '\n' + '5046:' + '\t' + str(round(df.tail(1)['5046'][0], 3)) + '\t' + str(anomalies['5046'][0]) +
            '\n\n' + 'message:' + '\t' +
            'Something wrong with the platform as there is a spike in [values where anomalies == 1].'
                )

问题是列值在每次运行中总是在变化我的意思是在这次运行中它的'10028', '1058', '20120', '20121', '20122', '20123', '5043', '5046' 但也许在下一次运行中它将是'10029', '1038', '20121', '20122', '20123', '5083', '5946'

如何根据数据框中存在的列动态创建详细信息,因为我不想硬编码,并且在消息中我想传递值为 1 的列的名称。

列的值将始终为 1 或 0。

【问题讨论】:

    标签: python python-3.x pandas dataframe numpy


    【解决方案1】:

    试试这个:

    # first part of the string
    s = '\n' + 'Metric Name' + '\t' + 'Count' + '\t' + 'Anomaly' 
    
    # dynamically add the data
    for idx, val in df.iloc[-1].iteritems():
        s += f'\n{idx}\t{val}\t{anomalies[idx][0]}' 
        # for Python 3.5 and below, use this
        # s += '\n{}\t{}\t{}'.format(idx, val, anomalies[idx][0])
        
    # last part
    s += ('\n\n' + 'message:' + '\t' +
          'Something wrong with the platform as there is a spike in [values where anomalies == 1].'
         )
    

    【讨论】:

    • 它给了我错误:- 文件“”,第 6 行 s += f'\n{idx}\t{val}\t{anomalies[idx ][0]}' ^ SyntaxError: 如果与任何错误相关,我正在使用 python 3 的语法无效
    • f 字符串格式可从 Python 3.6+ 获得。如果您使用早期版本,则需要将其更改为常规格式功能。
    • 非常感谢您的宝贵时间!
    • 嘿@Quang,知道如何在其中包含第三个数据框吗?
    猜你喜欢
    • 1970-01-01
    • 2021-12-28
    • 2020-12-27
    • 1970-01-01
    • 1970-01-01
    • 2022-07-06
    • 2020-04-09
    相关资源
    最近更新 更多