如何将ndarray值附加到特定列的数据帧行中?

时间:2018-12-26 12:30:42

标签: python pandas dataframe numpy-ndarray

我有一个函数可以返回一个ndarray

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

现在,我有一个数据帧df,其中包含A,B,C,...,Z列;但是我们得到的数组只有20个值。因此,我想找到一种方法,对于输出的每个数组,我都可以像这样将其存储在df中(A,B,W,X,Y,Z留为空白):

__| A | B | C | D | E | F | ...
0 |nan|nan| 0 | 1 | 0 | 0 | ...
1 |nan|nan| 1 | 1 | 0 | 1 | ...
.
. 
.

2 个答案:

答案 0 :(得分:3)

我为您的问题创建了一个小例子。希望对您有帮助

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)

输出:

    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

答案 1 :(得分:1)

通过这里发布的建议,我无法获得想要的东西。但是,我自己弄清楚了。我在这里分享以供社区参考。

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