Home > database >  drop alternate columns of csv file using pandas or python
drop alternate columns of csv file using pandas or python

Time:09-30

print("cols",cols)
for i in range(0, cols,2):
    print("i",i);
    dataset.drop(dataset.columns[dataset.iloc[:,i]], axis='1', inplace=True)
    
dataset.head()

Here cols is total number of columns in csv file( i am reading from my system).

Columns names in csv files is similar to ['time', 'Link 1 Bytes','L1 unit', 'Link 2 bytes','L2 unit', 'Link 2 bytes', 'L3 unit']. Here time, L1 unit, L2 unit and L3 unit plays no roles and are in text values.

Hence I want to keep only numerical value columns. Can anyone please help.

Moreover, I am getting the error, " IndexError: only integers, slices (:), ellipsis (...), numpy.newaxis (None) and integer or boolean arrays are valid indices"

CodePudding user response:

Solution 1: For dropping alternative items from list of columns;

lst = [1,2,3,4,5,6,7]
res = [lst[i] for i in range(len(lst)) if i % 2 != 0]

Solution 2: If want to drop columns with "unit" in it;

col_drop = [col for col in df.columns if "unit" in col]
df1 = df.drop(col_drop,axis=1)

Solution 3: If want to keep only numeric columns;

df1 = df.select_dtypes(include=numerics)

Hope this Helps...

  • Related