python - 无法将新的 DataFrame 写入 csv 文件

标签 python pandas dataframe

我正在尝试将新的数据帧写入 CSV 文件。但它没有被写入文件(空文件),也没有给出任何错误。

我觉得问题出在这一行。因为我正在尝试向该列写入单个值。

order['trade_type'] = trade_type

知道这里出了什么问题吗?

def write_transaction_to_file(trade_type):
    order = pd.DataFrame()
    order['trade_type'] = trade_type
    order.to_csv("open_pos.csv", sep='\t', index=False)


write_transaction_to_file('SELL')

最佳答案

您的代码创建一个 DataFrame,甚至没有列名称。

现在看看order['trade_type'] = trade_type

如果order包含一些行,那么在列中就有一个名为 'trade_type'(字符串)和trade_type(变量)是标量, 那么在 order 中的所有行中都会收到此值(在此列中)。

但是由于订单包含没有行,因此没有地方可以写入。

相反,您可以追加一行,例如:

order = order.append({'trade_type': trade_type}, ignore_index=True)

剩下的代码就OK了,输出文件名为普通字符串 也可以。

其他解决方案:只需创建一个具有单行和单行的 DataFrame 命名列,填充您的变量:

order = pd.DataFrame([[trade_type]], columns=['trade_type'])

然后像以前一样将其写入 CSV 文件。

关于python - 无法将新的 DataFrame 写入 csv 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58066401/

相关文章:

Python - 根据两列组合删除数据框中的重复项?

python - Pandas 数据框评估中的动态列名

python - Pandas : columns sample based on row value

Python创建与数据帧长度匹配的重复值列

python-如何使用另一列中的值作为 Pandas 中定义的字典的键来更新列?

python - 终止 scrapy 并保留输出文件

Python:在 json 中强制精度 float ?

python - 根据特定规则将 Pandas 数据框索引拆分为列

python - 如何用bottle.py批量上传图片?

apache-spark - Spark 写入 postgres 很慢