Akshay
Akshay

Reputation: 2763

Adding an extra index to Pandas DataFrame

I have a list of DataFrame, which is read something like this

data = [pd.read_csv(f, index_col=None, header=None) for f in temp]
flow = pd.DataFrame(data)

If I print the flow I get an output of

[[....
[128 rows x 14 columns]]
[128 rows x 14 columns]]
.
.
[128 rows x 14 columns]]]

So this means that each of the [128 rows x 14 columns] has one index, I have 60 as such. What I wanted to do was to read another CSV file which contains one column of data (60 rows) which looks something like this

[1 1 1 ... 2 2 2 ... 3 3 3]

I can read this by doing

new_data=pd.read_csv(f_new, index_col=None, header=None)

Now my question is can I keep everything as it is and just add the new_data as extra index, which should show something like this:

[[....
0 1 [128 rows x 14 columns]]
1 1 [128 rows x 14 columns]]
2 1 .
3 2 .
4 2 [128 rows x 14 columns]]]

Is this possible?

Upvotes: 2

Views: 4661

Answers (1)

MaxU - stand with Ukraine
MaxU - stand with Ukraine

Reputation: 210842

Try this:

flow = flow.set_index([flow.index, new_data]).rename_axis(['idx_col1','idx_col2'])

Upvotes: 3

Related Questions