如何使用pandas DataFrame to_csv附加标题?

时间:2019-12-21 03:31:32

标签: python pandas dataframe

sqldata = hiveSql.sql("""
        SELECT name,age from DB
""")

tabel_df = pd.DataFrame(data=sqldata.collect())
tabel_df.to_csv('resultRDD.csv')

如代码所示,我具有如下所示的CSV:

tom  16
jack 18

实际上,我需要如下所示的

name age
tom  16
jack 18

4 个答案:

答案 0 :(得分:1)

只需创建一个列名称列表:

table_df = pd.Dataframe(data=sqldata.collect())

#add these 2 lines
column_names = ['name','age']
table_df.columns = column_names

table_df.to_csv('resultRDD.csv')

就是这样。完成!

答案 1 :(得分:0)

您还可以传递列名列表,例如

tabel_df = pd.DataFrame(data=sqldata.collect(),columns=['name','age'])

答案 2 :(得分:0)

使用此:

$list = file('list.txt'); // opens list.txt into an array
$listcount = count($list); // counts the number of lines/array elements  
for ($x = 0; $x <= $listcount; $x++) //for loop to echo and delete each line
{
echo "\n $list[$x]\n"; 
unset($list[$x]); // deletes the lines that's just being echoed
file_put_contents("list.txt", $list); // puts the remaining contents of 
                                    //the array back into list.txt file
}

答案 3 :(得分:0)

以我自己的方式

tabel_df = pd.DataFrame(data=sqldata.collect(),columns=sqldata.columns)

也可以工作,谢谢所有