我正在尝试将新的数据帧写入 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/