简体   繁体   English

从pandas数据框创建np.array,该数据框有一列保存数组索引的值,另一列保存每个索引的值?

[英]Create np.array from pandas dataframe which has a column holding values of the array's indices and another column holding the value at each index?

I have a pandas DataFrame that looks like the following:我有一个如下所示的 pandas DataFrame:

x X y是的
0 0 2 2 4 4
1 1 3 3 1 1
2 2 5 5 9 9

All the x-values are unique.所有 x 值都是唯一的。 The x-values also tell the index of the corresponding number y in a numpy array. x 值还告诉 numpy 数组中相应数字 y 的索引。

I have an np.zeros array that has a shape of (6,).我有一个形状为 (6,) 的 np.zeros 数组。

How can I efficiently modify the np.zeros array such that it will turn into np.array([0, 0, 4, 1, 0, 9)?如何有效地修改 np.zeros 数组,使其变为 np.array([0, 0, 4, 1, 0, 9)? Notice how at index 2, the value is 4 because when x = 2, y = 4 according to the DataFrame.请注意索引 2 处的值为 4,因为根据 DataFrame,当 x = 2 时,y = 4。

Try:尝试:

arr = np.zeros(6)
arr[df["x"]] = df["y"]

print(arr)

Prints:印刷:

[0. 0. 4. 1. 0. 9.]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用熊猫从DataFrame或np.array中的列条目创建字典 - How to use Pandas to create Dictionary from column entries in DataFrame or np.array 在pandas.DataFrame中将np.array添加为列 - Adding an np.array as a column in a pandas.DataFrame 将np.array数据添加到熊猫数据框中的列后,是否可以对其排序? - Can I sort my np.array data once it has been added to a column in a pandas dataframe? AWS DLAMI中的Pandas np.array列 - Pandas np.array column in AWS DLAMI 从行索引,列索引和max(values)的np.array填充矩阵的快速方法 - Fast way to fill matrix from np.array of row index, column index, and max(values) 将 np.float64 和 np.array 值存储为 dataframe 中的列值 - Store np.float64 and np.array values as column values in dataframe 如果最小值满足条件,则获取二维np.array中每一行的最小值索引。 - Get the indices of min values for each row in a 2D np.array, if the min value satisfies a condition 如何在保留索引的同时将Pandas数据帧转换为np.array? - How to convert Pandas dataframe to np.array while preserving the index? Python:将 CSV 列解析为 np.array 的行和列索引? - Python: Parse a CSV column as a row and column index for a np.array? 如何在 Pandas 中将带有数字列表的列转换为 np.array 格式 - How to convert a column with list of numbers to np.array format in Pandas
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM