1

I wanna take array C2, size N,1, and make a array B, size N-1,1.

B[0] = C2[1]

B[1] = C2[2]

and so on. My code is:

import numpy as np
import pandas as pd

fields = "B:D"
data = pd.read_excel(r'C:\Users\file.xlsx', "Sheet2", usecols=fields)
N = 2

# Covariance calculation

C1 = data.cov() C2 = data.var()

B = np.zeros(shape=(N,1))

for i in B:
    B[i,1] = C2[i+1,1]

But the error is:

ValueError: Can only tuple-index with a MultiIndex

I know it is a simple mistake, but cant find where :S (new python user)

1 Answer 1

1

First, are you sure you need to be using numpy arrays? This seems like a job for python lists.

Next, what do you mean to be doing with for i in B:? what type is i?

In this case, iterating over B is going to set i to [0.], and you can now see that the next line is going to fail in the substitution

    B[[0.],i] = C2[[0.]+1,1]

In addition, the call to pd.var() returns a 1-d series, so the second index isn't doing anything.

I think you want to iterate over N like

for i in range(N):
    B[i,1] = C2[i+1]
Sign up to request clarification or add additional context in comments.

5 Comments

This way it tells me TypeError: 'int' object is not iterable
My mistake answering before coffee. Fixed above.
TypeError: can only concatenate list (not "int") to list Is it because of my variable types? Cs is Series (3,). B is float64 (3,1)
I see. The variance member function in pandas returns a series (which is like a 1-d array or vector), so there's only one index to specify the location within the Series. So your C2[i+1,1] should be C2[i+1]. You don't need the second index.
Works! Thank you! for i in range(N): B[i] = C2[i+1]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.