简体   繁体   English

从 Pandas 数据框列单独创建 numpy 数组

[英]Create separately numpy arrays from pandas dataframe columns

I would like to create automatically in Python n of numpy arrays from my pandas dataframe columns.我想从我的 Pandas 数据帧列在 Python n 的 numpy 数组中自动创建。 I can do this manually using for example:我可以手动执行此操作,例如:

numpy_array_1 = data_frame.column_1.values
numpy_array_2 = data_frame.column_2.values
...
numpy_array_n = data_frame.column_n.values

But I can not know how I should write code to create those arrays automatically.但我不知道我应该如何编写代码来自动创建这些数组。

You can simply use a for and loop through it.您可以简单地使用for并循环遍历它。 Remember that using (list(data_frame)) returns a list of the column names in the dataframe:请记住,使用(list(data_frame))返回数据框中列名的列表:

np_array = []
for i in list(data_frame):
    np_array.append(data_frame[i].values)

The expected output is a list that contains sublists of values.预期输出是一个包含值子列表的列表。 Where each sublist matches the position of the columns in the dataframe.每个子列表与数据框中列的位置相匹配。 Therefore you can either make a dictionary, or a tuple out of it.因此,您可以制作字典,也可以从中制作一个元组。 Dictionary example:字典示例:

np_array_dict = {}
for i in list(data_frame):
    np_array_dict[i] = data_frame[i].values

Suppose we have a simple df:假设我们有一个简单的 df:

df = pd.DataFrame({"0":[1,2], "1":[3,4]})
df 
   0  1
0  1  3
1  2  4

Then you can run:然后你可以运行:

for (key,value) in df.to_dict("list").items():
    exec("numpy_array_{} = np.array({})".format(key, value))

You'll get:你会得到:

numpy_array_0
array([1, 2])

numpy_array_1
array([3, 4])

and so on.等等。

Alternatively:或者:

for col in list(df):
    exec("numpy_array_{} = df[str({})].values".format(col,col))

您可以获得所有数据帧行和列值的矩阵,就像 df.values 一样简单您真的需要每列不同的数组吗?

This can be done without using loops:这可以在不使用循环的情况下完成:

df = pd.DataFrame({"0":[1,2], "1":[3,4], "2":[5,6]})
print(df)

   0  1  2
0  1  3  5
1  2  4  6

and then:进而:

[*np.transpose(df.values)]

results in:结果是:

[array([1, 2]), array([3, 4]), array([5, 6])]

and if a dictionary is desired one just needs to proceed as follows:如果需要一本字典,只需按以下步骤进行:

dict(zip(range(df.shape[1]), [*np.transpose(df.values)]))

which gives:这使:

{0: array([1, 2]), 1: array([3, 4]), 2: array([5, 6])}

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM