CSV write operation pandas

Read CSV

When reading the CSV file ,, sep parameter set may be replaced with the code division:

df = pd.read_csv('student_scores.csv', sep=':')
df.head()

This allows the colon as the delimiter.

 

read_csv Another function which line the specified file as a title, but the title specifies the column labels. Is usually the first line of the title, but sometimes if the top of the file additional meta information, we want to specify another row as the title. You can do this:

df = pd.read_csv('student_scores.csv', header=2)
df.head()

As used herein the second line as a title, and all their data will be deleted. By default, read_csv the use of header = 0, using the first row as column labels.

If the file does not include column labels may be used  header=None to prevent the first row of data being erroneously as column labels.

 

You can also specify your own column labels in the following ways:

labels = ['id', 'name', 'attendance', 'hw', 'test1', 'project1', 'test2', 'project2', 'final']
df = pd.read_csv('student_scores.csv', names=labels)
df.head()

 

In addition to the default index (an integer incremented from 0 to 1), but also one or more columns may be designated as the index data frame:

df = pd.read_csv('student_scores.csv', index_col='Name')
df.head()

df = pd.read_csv('student_scores.csv', index_col=['Name', 'ID'])
df.head()

Write CSV

df_powerplant.to_csv('powerplant_data_edited.csv')
df = pd.read_csv('powerplant_data_edited.csv')
df.head()

This  Unnamed:0 is the to_csv() default save index, unless you specify is not saved. To ignore the index, you must provide parameters index=False:

df_powerplant.to_csv('powerplant_data_edited.csv', index=False)
df = pd.read_csv('powerplant_data_edited.csv')
df.head()

Guess you like

Origin www.cnblogs.com/shenxi-ricardo/p/12123845.html