Skip to content Skip to sidebar Skip to footer

How To Use Pandas To Select Certain Columns In Csv File

I only just started my coding journey in order to and have watched a bunch of tutorials on youtube and am now trying to 'import' a dataset from SPSS into python using jupyter. So

Solution 1:

Use this:

import pandas as pd
df = pd.read_csv('csvfile.csv' , usecols = ['col1','col2'])
df

Inplace of 'col1' and 'col2' enter the column names. Then to write them into another csv , do this:

df.to_csv('csv_file_1.csv' , index = False)

Solution 2:

You can select columns by their names.

import pandas as pd 
df = pd.read_csv('csvfile.csv')
final_df = df[['col1','col2','col3']]

or you can select them by indexes

final_df = df.iloc[:,[0,1,2]]

Post a Comment for "How To Use Pandas To Select Certain Columns In Csv File"