首先,我从data0创建了一个csv文件,如图所示:
data0 = ["car", 0.82, 0.0026, 0.914, 0.59]
test_df = pd.DataFrame([data0])
test_df.to_csv("testfile1.csv")
输出的";testfile1.csv";显示如下:
0 1 2 3 4
0 car 0.82 0.0026 0.914 0.59
我想将新数据(data1=["bus",0.90.123,12.907,42],data2=["van",0.23,0.41,.031,0.8946.16,4.104](附加到旧的csv文件中,以便它出现在新行中,但正好在前几行下,如下所示:
0 1 2 3 4 5 6
0 car 0.82 0.0026 0.914 0.590 NaN NaN
1 bus 0.90 0.1230 12.907 42.000 NaN NaN
2 van 0.23 0.4100 0.031 0.894 6.16 4.104
我尝试了使用.append((或.to_csv((的程序和其他类似方法,模式为";a":
test_df = pd.read_csv("testfile1.csv", index_col=0)
test_df = test_df.append([data1], ignore_index=True)
test_df = test_df.append([data2], ignore_index=True)
test_df.to_csv("testfile1.csv")
但是,每次将新数据附加到新列中而不是以前的列下时:
0 1 2 3 4 ... 0 1 2 3 4
0 NaN NaN NaN NaN NaN ... car 0.82 0.0026 0.914 0.59
1 bus 0.90 0.123 12.907 42.000 ... NaN NaN NaN NaN NaN
2 van 0.23 0.410 0.031 0.894 ... NaN NaN NaN NaN NaN
我的项目是读取现有的CSV文件,将其附加并保存回同一个文件。我甚至试着给熊猫打字。系列
您可能想先将列表转换为熊猫系列:
data1 = ['bus', 0.90, 0.1230, 12.907, 42.000]
row1 = pd.Series(data1)
data2 = ["van", 0.23, 0.41, .031, 0.894, 6.16, 4.104]
row2 = pd.Series(data2)
然后附加:
test_df = test_df.append(row1, ignore_index=True)
test_df = test_df.append(row2, ignore_index=True)
输出:
0 1 2 3 4 5 6
0 car 0.82 0.0026 0.914 0.590 NaN NaN
1 bus 0.90 0.1230 12.907 42.000 NaN NaN
2 van 0.23 0.4100 0.031 0.894 6.16 4.104