python - 从 pandas 列动态创建字符串

标签 python python-3.x pandas dataframe numpy

我有两个数据框,如下所示,一个是 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)

enter image description here

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

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。

最佳答案

试试这个:

# 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].'
     )

关于python - 从 pandas 列动态创建字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65360877/

相关文章:

python-3.x - 批量读取Cifar10数据集

python - glBufferSubData ,尚未实现列表的类型推断 - 实例化渲染

python - '值错误: could not convert string to float' in python sklearn

python - Pandas 尝试向数据帧追加一行,但不断覆盖现有行

python - 验证 ModelForm 时出现问题

python - 为什么我的程序使用 .py 扩展名但不能使用 .pyw 扩展名?

python - 如何从数组写入 Excel 中的整行 - xlwt

python - 读取许多文件并在 Pandas 中创建列

python - Django Rest Framework 不从条件返回响应代码

python - 在 pandas 中添加行终止符最终会添加另一个\r