Concatenating columns as an index in Pandas

I am importing a text file into pandas and would like to combine 3 columns from the file to make an index.

I am open to this in 1 or more steps. I can either do the conversion at the same time when I create the DataFrame, or I can create the DataFrame and rebuild it using the newly created column. Knowing how to do this in both directions would be most useful to me.

In the end, I would like the index to be the value to concatenate the values ​​in the first three columns.

+6
source share
2 answers

If your columns are composed of rows, you can simply use the + operator (adding in the context of the rows is to concatenate them in python, and pandas follows this):

 In [1]: import pandas as pd In [2]: df = pd.DataFrame({'year':['2012', '2012'], 'month':['01', '02']}) In [3]: df Out[3]: month year 0 01 2012 1 02 2012 In [4]: df['concatenated'] = df['year'] + df['month'] In [5]: df Out[5]: month year concatenated 0 01 2012 201201 1 02 2012 201202 

And then, if this column is created, you can simply use set_index to change the index

 In [6]: df = df.set_index('concatenated') In [7]: df Out[7]: month year concatenated 201201 01 2012 201202 02 2012 

Please note that pd.concat is not “concatenating rows”, but combining rows / data to add columns or rows of different data frames or rows together into one data frame (not several rows / columns in one row / column). See http://pandas.pydata.org/pandas-docs/dev/merging.html for a detailed explanation of this.

+9
source

If you use read_csv to import a text file, there is an index_col argument, which you can pass a list of column names or numbers to. This will lead to the creation of MultiIndex - I'm not sure if this suits your application.

If you want to explicitly combine your index together (assuming these are strings), it looks like you can do it with the + operator. (Warning, unverified code ahead)

 df['concatenated'] = df['year'] + df['month'] df.set_index('concatenated') 
0
source

Source: https://habr.com/ru/post/950119/


All Articles