为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

米脂 2021-09-25 21:57:17
我有一个返回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 | ..... .
查看完整描述

1 回答

?
偶然的你

TA贡献1841条经验 获得超3个赞

我无法通过此处发布的建议获得我想要的东西。不过,我自己也弄明白了。我在这里分享它以供社区参考。


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 

//img1.sycdn.imooc.com//614f2b020001969e15260215.jpg

查看完整回答
反对 回复 2021-09-25
  • 1 回答
  • 0 关注
  • 185 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号