Home > other >  Diagonal Extraction using Pandas
Diagonal Extraction using Pandas

Time:09-29

diagonal Excel CHART

So I'm attempting to extract this diagonal of numbers from .csv file I imported .But using .loc doesn't allow me to extract more than 3 indexing (IndexingError: Too many indexers).

import pandas as pd

df = pd.read_csv('Norm1.csv')

tf = df.loc[0:0,"BMP2"]
 
cf = df.loc[1:1,"BTR60"]

df = df.loc[2:2,"BTR70"]

ef = df.loc[3:3,"M1"]

hf = df.loc[4:4,"M109"]

jf = df.loc[5:5,"M110"]

kf = df.loc[6:6,"M113"]

lf = df.loc[7:7,"M2"]

pf = df.loc[8:8,"M35"]

of = df.loc[9:9,"M548"]

uf = df.loc[10:10,"T72"]

yf = df.loc[11:11,"Zil-131"]


print(tf.to_string()) 
print(cf.to_string())
print(df.to_string()) 
print(ef.to_string())
print(hf.to_string()) 
print(jf.to_string())
print(kf.to_string()) 
print(lf.to_string())
print(pf.to_string()) 
print(of.to_string())
print(uf.to_string()) 
print(yf.to_string())

I know there's a simpler way to do this can anyone assist ?

CodePudding user response:

Use df.iloc[row, col] instead.

diag = []

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

CodePudding user response:

Use numpy.diag.

import numpy as np

out = np.diag(df)

# If you need it back as a dataframe:
out = pd.DataFrame([out], columns=df.columns)
  • Related