【问题标题】:Values in Wrong Columns After Pandas DataFrame.to_csv()Pandas DataFrame.to_csv() 后列中的值错误
【发布时间】:2015-04-03 02:56:49
【问题描述】:

我正在使用 Pandas 连接两个数据文件。 concat 运行良好,但是当我将数据写回 csv 时,数据会失去一些连贯性:

# Define DataFrame 1
headerList1 = ['A', 'B', 'C', 'D']
b1 = np.array([[0, 'B_foo', 2, 'D_one'],
              [3, 'B_bar', 5, 'D_two'],
              [6, 'B_cat', 8, 'D_one']])
df1 = pd.DataFrame(b1, columns=headerList1)

# Define DataFrame 2
headerList2 = ['C', 'E', 'F', 'G']
b2 = np.array([[12, 'E_foo', 2, 'G_one'],
              [15, 'E_bar', 5, 'G_two'],
              [19, 'E_cat', 8, 'G_one']])
df2 = pd.DataFrame(b2, columns=headerList2)

# Concat DataFrames
df3 = pd.concat([df1, df2], axis=0, ignore_index=True)

# Write to csv
scratchFile = os.path.join(dir, 'scratch.csv')
df3.to_csv(scratchFile, index_label=False, ignore_index=True)

我正在寻找:

  A      B   C      D      E    F      G
  0  B_foo   2  D_one    NaN  NaN    NaN
  3  B_bar   5  D_two    NaN  NaN    NaN
  6  B_cat   8  D_one    NaN  NaN    NaN
NaN    NaN  12    NaN  E_foo    2  G_one
NaN    NaN  15    NaN  E_bar    5  G_two
NaN    NaN  19    NaN  E_cat    8  G_one

但得到:

A     B     C       D       E       F       G
0     0     B_foo   2     D_one   Nan     Nan
1     3     B_bar   5     D_two   Nan     Nan
2     6     B_cat   8     D_one   Nan     Nan
3    Nan    Nan     12    Nan     E_foo    2     G_one
4    Nan    Nan     15    Nan     E_bar    5     G_two
5    Nan    Nan     19    Nan     E_cat    8     G_one

我几乎可以通过从 to_csv() 命令中删除 index_label=False 来达到所需的结果,但这会导致添加不需要的索引列。

有没有办法在没有索引列的情况下获得所需的输出?另外,出于个人兴趣,为什么删除 index_label=False 会破坏列组织?

谢谢!

【问题讨论】:

    标签: python pandas


    【解决方案1】:
    df3.to_csv('df3.csv', index = False)
    

    这对我有用。 index = False 表示数据帧索引不包含在 csv 中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-07
      • 1970-01-01
      • 1970-01-01
      • 2015-01-04
      • 1970-01-01
      • 2015-05-30
      • 2023-03-16
      • 1970-01-01
      相关资源
      最近更新 更多