Paradox Paradox - 23 days ago 8
Python Question

Python co-occurrence matrix, how to multiply row/column by integer?

I have a co-occurrence matrix of the following form:

Cat Dog Zebra
Cat 0 2 3
Dog 2 0 1
Zebra 3 1 0


which has been generated with the python pandas library. Let's say that the its data frame is stored in the variable
df
and I have another integer variable
x
. Then how could I multiply all values for an animal by my variable
x
?

For example, if my variable x = 2 and animal = Dog, then the matrix would look like this:

Cat Dog Zebra
Cat 0 4 3
Dog 4 0 2
Zebra 3 2 0

Answer

To multiply a row:

df.loc['Dog', :] = df.loc['Dog', :] * x

To multiply a column:

df['Dog'] = df['Dog'] * x

See this page for more info: http://pandas.pydata.org/pandas-docs/stable/indexing.html