How to append ndarray values into dataframe rows of particular columns?

Viewed 199

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 Answers

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

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

Related