将值导出到现有 excel 文件的同一列
Exporting values to existing excel file to same column
我每天都在 运行 编写一个脚本来获取我保存为数据框的日期和值。像这样:
df.head(4)
Date Value
11/02/2021 00:00:00 550
11/02/2021 01:00:00 582
11/02/2021 02:00:00 655
11/02/2021 03:00:00 773
如果我使用命令 'df.to_csv("file.csv")',我会在 excel sheet 中得到我的数据框。但是,当我 运行 第二天 (12/02/2021) 的脚本时,我想获得相同 excel sheet 的值。我该怎么做?
如果我在 2021 年 2 月 12 日使用 'df.to_csv("file.csv")',它将删除我前一天的表格并用新值替换它们。我想每天 运行 脚本并将其保存在相同的 sheet (所有值)上。有什么方法可以将值始终保存在同一列中,同时保留过去的值并添加新值?
您可以将文件作为数据框读入,附加新值,然后再次写出文件。
df_out = pd.read_csv('file.csv')
df_out = df_out.append(df)
df_out.to_csv('file.csv')
不用在python中打开直接使用,在append
模式下用df.to_csv(df, mode='a')
打开。我写了一些小例子
# EXAMPLE
a = np.zeros((2,3))
b = np.ones((5,3))
df_a = pd.DataFrame(a, columns = ['a','b','c'])
df_b = pd.DataFrame(b, columns = ['a','b','c'])
df_a.to_csv('test.csv')
df_b.to_csv('test.csv', mode='a', header = False)
# mode = 'a', is the append mode, if you don't write it is 'w' - write, by default
# header = False, in order not to repeat header in the middle
我每天都在 运行 编写一个脚本来获取我保存为数据框的日期和值。像这样:
df.head(4)
Date Value
11/02/2021 00:00:00 550
11/02/2021 01:00:00 582
11/02/2021 02:00:00 655
11/02/2021 03:00:00 773
如果我使用命令 'df.to_csv("file.csv")',我会在 excel sheet 中得到我的数据框。但是,当我 运行 第二天 (12/02/2021) 的脚本时,我想获得相同 excel sheet 的值。我该怎么做?
如果我在 2021 年 2 月 12 日使用 'df.to_csv("file.csv")',它将删除我前一天的表格并用新值替换它们。我想每天 运行 脚本并将其保存在相同的 sheet (所有值)上。有什么方法可以将值始终保存在同一列中,同时保留过去的值并添加新值?
您可以将文件作为数据框读入,附加新值,然后再次写出文件。
df_out = pd.read_csv('file.csv')
df_out = df_out.append(df)
df_out.to_csv('file.csv')
不用在python中打开直接使用,在append
模式下用df.to_csv(df, mode='a')
打开。我写了一些小例子
# EXAMPLE
a = np.zeros((2,3))
b = np.ones((5,3))
df_a = pd.DataFrame(a, columns = ['a','b','c'])
df_b = pd.DataFrame(b, columns = ['a','b','c'])
df_a.to_csv('test.csv')
df_b.to_csv('test.csv', mode='a', header = False)
# mode = 'a', is the append mode, if you don't write it is 'w' - write, by default
# header = False, in order not to repeat header in the middle