Home > Back-end >  how slice by hybrid stile
how slice by hybrid stile

Time:02-04

having a random df

df = pd.DataFrame([[1,2,3,4],[4,5,6,7],[7,8,9,10],[10,11,12,13],[14,15,16,17]], columns=['A', 'B','C','D'])
cols_in = list(df)[0:2] list(df)[4:]

now:

x = []
for i in range(df.shape[0]):
   x.append(df.iloc[i,cols_in])  

obviously in the cycle, x return an error due to col_in assignment in iloc.

How could be possible apply a mixed style slicing of df like in append function ?

CodePudding user response:

It seems like you want to exclude one column? There is no column 4, so depending on which columns you are after, something like this might be what you are after:

df = pd.DataFrame([[1,2,3,4],[4,5,6,7],[7,8,9,10],[10,11,12,13],[14,15,16,17]], columns=['A', 'B','C','D'])

If you want to get the column indeces from column names you can do:

cols = ['A', 'B', 'D']
cols_in = np.nonzero(df.columns.isin(cols))[0]


x = []
for i in range(df.shape[0]):
   x.append(df.iloc[i, cols_in].to_list()) 
x 

Output:

[[1, 2, 4], [4, 5, 7], [7, 8, 10], [10, 11, 13], [14, 15, 17]]
  •  Tags:  
  • Related