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.
To set column names of DataFrame in Pandas, use pandas. DataFrame. columns attribute. Assign required column names as a list to this attribute.
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 .
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.
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'])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With