Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pandas: dataframe to_csv, how to set column names

Code snippet:

import numpy as np
import pandas as pd
myseries=pd.Series(np.random.randn(5))
df=pd.DataFrame(myseries)
df.to_csv("output.csv")

Output:

      0
0    0.51..
1    0.14..
2    -0.68..
3    0.48..
4    1.89..

I want the column name to be "values" instead of 0. How can I do that?
I suppose that I should replace the last statement with df.to_csv("output.csv", columns = ["values"]). But I got the keyerror: u"None of [['values']] are in the [columns]" I don't know what that means.

[update]
Many answers say that I should use df.columns=['values']. Well, that does not work for me. I concern not only what the dataframe is like, but also what the csv file is like. The dataframe looks all right, but the csv file is not. That's the confusing part.

...
df.columns=["values"]
df.to_csv("output.csv")

It says:IOError: [Errno 13] Permission denied: 'output.csv'.
I then use the absolute path "C:\Users\myname\Desktop\output.csv", the error is like: IOError: [Errno 13] Permission denied: 'C:\\Users\\myname\\Desktop\\output.csv' I don't know why this error, but this is rather confusing.
For further information, I installed anaconda-2.7 on win10. I tested the code with spyder.

like image 757
dudu Avatar asked Aug 16 '18 13:08

dudu


People also ask

How do I assign a column name to a DataFrame in Pandas?

To set column names of DataFrame in Pandas, use pandas. DataFrame. columns attribute. Assign required column names as a list to this attribute.

How do I name a column in Pandas CSV?

Call pandas. read_csv(filepath_or_buffer, names = None) with filepath_or_buffer set to the filename of the . csv and names set to the list of column names. The column names will be assigned to each column of the resultant DataFrame in the order they appear in names .

What does To_csv do in Pandas?

Pandas DataFrame to_csv() function converts DataFrame into CSV data. We can pass a file object to write the CSV data into a file. Otherwise, the CSV data is returned in the string format.


1 Answers

You can set column name in DataFrame constructor:

df = pd.DataFrame(myseries, columns=['values'])
df.to_csv("output.csv")

Or:

df = pd.DataFrame({'values':myseries})
print (df)
     values
0 -0.429758
1 -0.019931
2  1.189596
3  1.309223
4 -0.337061

df.to_csv("output.csv")

Or set parameter header in DataFrame.to_csv:

df = pd.DataFrame(myseries)
df.to_csv("output.csv", header=['values'])

Or in Series.to_csv:

myseries.to_csv("output.csv", header=['values'])
like image 174
jezrael Avatar answered Sep 24 '22 18:09

jezrael