【问题标题】:How to append new row to csv file with pandas?如何使用熊猫将新行附加到csv文件?
【发布时间】:2017-07-28 12:20:02
【问题描述】:

我想将从 mosquitto broker 收到的数据保存为 csv 文件。下面是mqtt_subscribe.py的脚本

import paho.mqtt.client as mqtt
import pandas as pd

def on_connect(client, userdata, rc):
    print("Connected with result code "+str(rc))
    client.subscribe("test")

def on_message(client, userdata, msg):
    print str(msg.payload)
    datas = map(int, msg.payload)
    df = pd.DataFrame(data=datas, columns=['numbers'])

    f = open("test.csv", 'a')
    df.to_csv(f)
    f.close()

client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message

client.connect("localhost", 1883, 60)

client.loop_forever()

此脚本将打印从代理收到的随机数/数据(直到我手动停止脚本),如下所示(示例)

Connected with result code 0
4
7
7

我希望把这个结果写成这样的 CSV 文件

,numbers
0,4
1,7
2,7

但我得到了这个

,numbers
0,4
,numbers
0,7
,numbers
0,7

我在这里遗漏了什么吗?我相信这是因为on_message 方法不断用列覆盖数据框,但我不知道除了on_message 方法之外,我应该在哪里初始化数据框。

提前谢谢你。

【问题讨论】:

  • 试试df.to_csv(f, header=False)

标签: python csv pandas


【解决方案1】:

您可以使用类似这样的方法将 panda 数据帧 df 附加到 test.csv 而不包括标题:

with open('test.csv', 'a') as csv_file:
    df.to_csv(csv_file, header=False)

'with open' 的使用帮助我们不必为显式关闭文件而烦恼

【讨论】:

    猜你喜欢
    • 2018-06-18
    • 1970-01-01
    • 2018-05-24
    • 2018-09-29
    • 2022-12-24
    • 2014-01-27
    • 2017-04-18
    • 2017-01-04
    • 2018-05-16
    相关资源
    最近更新 更多