3

I have a function that returns an ndarray like this

[0 1 0 0 0 0 1 0 1 0 1 0 0 1 0 0 0 0 0 0] 

Now, I have a data frame df with columns A,B,C,...,Z ; but the array we are getting has only 20 values. Hence I want to find a way such that for every array I get as output, I am able to store it in df like this (A,B,W,X,Y,Z are to be left blank):

__| A | B | C | D | E | F | ...
0 |nan|nan| 0 | 1 | 0 | 0 | ...
1 |nan|nan| 1 | 1 | 0 | 1 | ...
.
. 
.
2
  • 2
    If 20 values are present in the array, which columns do you want as blank? Last 6? Commented Dec 26, 2018 at 12:34
  • These are the columns: A, B, W,X,Y,Z Commented Dec 26, 2018 at 12:55

2 Answers 2

3

i have created small example of your problem. hope it helps

import pandas as pd
import numpy as np

df = pd.DataFrame(np.nan, index=[0, 1, 2, 3], columns=['A', 'B', 'C'])
data = np.array([[0, 1],
                   [1, 1]])
print(df)
# df[['B', 'C']] = pd.DataFrame.from_records(data)
df[['B', 'C']] = pd.DataFrame(data)

print(df)

output:

    A   B   C
0 NaN NaN NaN
1 NaN NaN NaN
2 NaN NaN NaN
3 NaN NaN NaN

    A    B    C
0 NaN  0.0  1.0
1 NaN  1.0  1.0
2 NaN  NaN  NaN
3 NaN  NaN  NaN
Sign up to request clarification or add additional context in comments.

6 Comments

from_records is redundant.
@MayankPorwal i tried with iloc first but it didn't work. do you have any idea why?
i tried like this df.iloc[:, 1:] = pd.DataFrame(data)
You don't need iloc either. This should work: df[['B', 'C']] = pd.DataFrame(data).
thank you for your solution, but I wish to append the rows as they come from the function. Can you help me with that? Thanks!
|
1

I couldn't get what I wanted through the suggestions posted here. However, I did figure it out myself. I'm sharing it here for the community's reference.

import pandas as pd
import numpy as np

df = pd.DataFrame(columns=[chr(i) for i in range(ord('A'),ord('Z')+1)])

print(df)
Empty DataFrame
Columns: [A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z]
Index: []

[0 rows x 26 columns]
list1 = [i for i in range(101,121)]
arr1d = np.array(list1)

arr1d
array([101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113,
       114, 115, 116, 117, 118, 119, 120])
# Create alphabet list of uppercase letters
alphabet = []
for letter in range(ord('C'),ord('W')):
    alphabet.append(chr(letter))
alphabet
['C',
 'D',
 'E',
 'F',
 'G',
 'H',
 'I',
 'J',
 'K',
 'L',
 'M',
 'N',
 'O',
 'P',
 'Q',
 'R',
 'S',
 'T',
 'U',
 'V']
df = df.append(pd.Series(arr1d, index=alphabet), ignore_index=True)
#This line of code can be used for every new value of arr1d 

enter image description here

Comments

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.