简体   繁体   中英

Create a dataframe from arrays python

I'm try to construct a dataframe (I'm using Pandas library) from some arrays and one matrix.

in particular, if I have two array like this:

A=[A,B,C]
B=[D,E,F]

And one matrix like this :

1 2 2
3 3 3
4 4 4

Can i create a dataset like this?

  A B C
D 1 2 2
E 3 3 3
F 4 4 4

Maybe is a stupid question, but im very new with Python and Pandas.

I seen this :

https://pandas.pydata.org/pandas-docs/version/0.23.4/generated/pandas.DataFrame.html

but specify only 'colums'.

I should read the matrix row for row and paste in my dataset, but I m think that exist a more easy solution with Pandas.

This should do the trick for you.

columns = ["A", "B", "C"]
rows = ["D", "E", "F"]
data = np.array([[1, 2, 2], [3, 3, 3],[4, 4, 4]])
df = pd.DataFrame(data=data, index=rows, columns=columns)

You can do like this:

a=[[1, 2, 2],[1, 2, 2],[1, 2, 2]]
df=pd.DataFrame(a)
df.columns = ['a', 'b', 'c']
df.index = ['d', 'e', 'f']
print(df)

is this what you need?

import pandas as pd
A=['A','B','C']
B=['D','E','F']
C=[[1,2,2],[3,3,3],[4,4,4]]

df=pd.DataFrame(C, columns=A)
df.index=B
df.head()

    A   B   C
D   1   2   2
E   3   3   3
F   4   4   4

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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