从列表中添加数据框中的列 [英] Add column in dataframe from list

查看:125
本文介绍了从列表中添加数据框中的列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有某些列的数据框,如下所示:

I have a dataframe with some columns like this:

A   B   C  
0   
4
5
6
7
7
6
5

A中可能的值范围仅为0到7 .

我还列出了8个这样的元素:

Also, I have a list of 8 elements like this:

List=[2,5,6,8,12,16,26,32]  //There are only 8 elements in this list

如果A列中的元素是 n ,我需要将List中的 n 个元素插入新列,例如'D'.

If the element in column A is n, I need to insert the n th element from the List in a new column, say 'D'.

如何一口气做到这一点而又不遍历整个数据框?

How can I do this in one go without looping over the whole dataframe?

结果数据框如下所示:

A   B   C   D
0           2
4           12
5           16
6           26
7           32
7           32
6           26
5           16

注意:数据框很大,迭代是最后一个选项.但是如果需要的话,我也可以将其他数据结构(例如dict)布置在列表"中的元素.

Note: The dataframe is huge and iteration is the last option option. But I can also arrange the elements in 'List' in any other data structure like dict if necessary.

推荐答案

IIUC,如果将您的(不幸的是)List制成ndarray,则可以自然地将其编入索引.

IIUC, if you make your (unfortunately named) List into an ndarray, you can simply index into it naturally.

>>> import numpy as np
>>> m = np.arange(16)*10
>>> m[df.A]
array([  0,  40,  50,  60, 150, 150, 140, 130])
>>> df["D"] = m[df.A]
>>> df
    A   B   C    D
0   0 NaN NaN    0
1   4 NaN NaN   40
2   5 NaN NaN   50
3   6 NaN NaN   60
4  15 NaN NaN  150
5  15 NaN NaN  150
6  14 NaN NaN  140
7  13 NaN NaN  130

在这里我建立了一个新的m,但是如果您使用m = np.asarray(List),同样的事情也应该起作用:df.A中的值将选择m的适当元素.

Here I built a new m, but if you use m = np.asarray(List), the same thing should work: the values in df.A will pick out the appropriate elements of m.

请注意,如果您使用的是旧版本的numpy,则可能不得不使用m[df.A.values]-过去,numpy与其他版本的配合不好,并且某些重构在引起了一些头痛.现在情况有所改善.

Note that if you're using an old version of numpy, you might have to use m[df.A.values] instead-- in the past, numpy didn't play well with others, and some refactoring in pandas caused some headaches. Things have improved now.

这篇关于从列表中添加数据框中的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆