[英]How to do Mapping between Numpy Array and Pandas Dataframe?
我有一个像熊猫一样的数据帧
data = [[0, 10, 22000, 3],
[1, 15, 42135, 4],
[0, 14, 13526, 5],
[0, 16, 32156, 3],
[1, 23, 13889, 5],
[0, 18, 18000, 6],
[0, 21, 13189, 2],
[1, 32, 58766, 2]]
df = pd.DataFrame(data, columns = ['Gender', 'Age', 'Amount','Dependents'])
我有一个numpy阵列
arr = numpy.array([[1, 15, 42135, 4],
[1, 23, 13889, 5],
[0, 21, 13189, 2]])
在这里,我想在数据框'data'(比如说'Good_Bad')中创建一个新列,如果数组中存在数组,则为1。
结果应该是这样的
data = [[0, 10, 22000, 3, 0],
[1, 15, 42135, 4, 1],
[0, 14, 13526, 5, 0],
[0, 16, 32156, 3, 0],
[1, 23, 13889, 5, 1],
[0, 18, 18000, 6, 0],
[0, 21, 13189, 2, 1],
[1, 32, 58766, 2, 0]]
记录2,5,7在新列中有1,其他记录有0.不确定如何映射数组和数据帧。
方法#1
矢量化broadcasting
-
dfc = df[['Gender','Age','Amount','Dependents']] # select relevant cols
df['Good_Bad'] = (dfc.values[:,None]==arr).all(2).any(1).astype(int)
在较新的pandas版本(> = v0.24)上,使用dfc.to_numpy(copy=False)
而不是dfc.values
。
方法2
这是一个有内存和性能效率的views
-
# https://stackoverflow.com/a/45313353/ @Divakar
def view1D(a, b): # a, b are arrays
# This function gets 1D view into 2D input arrays
a = np.ascontiguousarray(a)
b = np.ascontiguousarray(b)
void_dt = np.dtype((np.void, a.dtype.itemsize * a.shape[-1]))
return a.view(void_dt).ravel(), b.view(void_dt).ravel()
D,A = view1D(dfc,arr)
df['Good_Bad'] = np.isin(D,A).astype(int)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.