【问题标题】:Pandas Dataframe to CSV, but writing n rows lowerPandas Dataframe 到 CSV,但写下 n 行
【发布时间】:2021-09-24 18:29:01
【问题描述】:

给定一个 3x3 的数据框,在将数据框转换为 CSV 文件时,索引和列名将作为行/列本身包含在内,我如何将表格向下移动 1 行? p>

我想在使用完全独立的列表后向下移动 1 行,留下 1 个空行写入 CSV。

下面的代码和 cmets 包含关于我的目标的更多细节和清晰度:

import pandas as pd
separate_row = [' ', 'Z', 'Y', 'X']

# Note: The size is 3x3
x = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
header_cols = ['a','b','c']
df = pd.DataFrame(x, index=[1,2,3], columns=header_cols)

# Note: Exporting as 4x4 now
df.to_csv('data.csv', index=True, header=True)

# How to make CSV file 5x4??

CSV 文件中的第 1 行将由 separate_row 填充,尽管在创建数据框时我不能将 separate_row 作为列名。列名必须是header_cols,但separate_row 是在上面。

【问题讨论】:

标签: python pandas list dataframe csv


【解决方案1】:

试试:

with open('data.csv', 'w') as csvfile:
    pd.DataFrame(columns=separate_row).to_csv(csvfile, index=None)
    df.to_csv(csvfile, index=True, header=True)
>>> %cat data.csv
 ,Z,Y,X
,a,b,c
1,0,0,0
2,0,0,0
3,0,0,0

【讨论】:

    【解决方案2】:

    您可以将换行符写入文件,然后附加数据框:

    import pandas as pd
    
    # Note: The size is 3x3
    x = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
    df = pd.DataFrame(x, index=[1,2,3], columns=['a','b','c'])
    
    
    
    with open('data.csv', 'w') as f:
        f.write('\n')
    
    
    df.to_csv('data.csv', index=True, header=True, mode='a')
    

    【讨论】:

    • 我不清楚,但我认为 OP 不想要空行,他想要 separate_row
    猜你喜欢
    • 2019-12-18
    • 2014-02-07
    • 2018-09-10
    • 2013-05-31
    • 1970-01-01
    • 2018-01-09
    • 2021-04-22
    相关资源
    最近更新 更多