Delete row and column from pandas dataframe

Viewed 267

I have a CSV file which is contains a symmetric adjacency matrix which means row and column have equivalent labels.

I would like to import this into a pandas dataframe, ideally have some GUI pop up and ask for a list of items to delete....and then take that list in and set the values in the relative row and column as zero's and return a separate altered dataframe.

In short, something that takes the following matrix

a b c d e

a 0 3 5 3 5

b 3 0 2 4 5

c 5 2 0 1 7

d 3 4 1 0 9

e 5 5 7 9 0

Pops up a simple interface asking "which regions should be deleted" and a line to enter those regions

and say c and e are entered

returns

a b c d e

a 0 3 0 3 0

b 3 0 0 4 0

c 0 0 0 0 0

d 3 4 0 0 0

e 0 0 0 0 0

with the altered entries as shown in bold

it should be able to do this for as many areas as entered which can be up to 379....ideally seperated by commas

2 Answers

Set columns and rows by index values with DataFrame.loc:

vals = ['c','e']
df.loc[vals, :] = 0

df[vals] = 0
#alternative
#df.loc[:, vals] = 0
print (df)
   a  b  c  d  e
a  0  3  0  3  0
b  3  0  0  4  0
c  0  0  0  0  0
d  3  4  0  0  0
e  0  0  0  0  0

Another solution is create boolean mask with numpy broadcasting and set values by DataFrame.mask:

mask = df.index.isin(vals) | df.columns.isin(vals)[:, None]
df = df.mask(mask, 0)
print (df)
   a  b  c  d  e
a  0  3  0  3  0
b  3  0  0  4  0
c  0  0  0  0  0
d  3  4  0  0  0
e  0  0  0  0  0

Start by importing the csv:

import pandas as pd
adj_matrix = pd.read_csv("file/name/to/your.csv", index_col=0)

Then request the input:

regions = input("Please enter the regions that you want deleted (as an array of strings)")
adj_matrix.loc[regions, :] = 0
adj_matrix.loc[:, regions] = 0

Now adj_matrix should be in the form you want.

Related