Monday, 8 April 2024

Pandas: Swap index levels in a multi index data frame

Using swaplevel() method, we can swap the index levels in a multi index data frame.

Let’s use below data set to demonstrate the examples.

       Name  Age       City  Gender  Rating
0   Krishna   34  Bangalore    Male      39
1     Sailu   35  Hyderabad  Female      43
2      Joel   29  Hyderabad    Male      67
3     Chamu   35    Chennai  Female     100
4  Jitendra   52  Bangalore    Male      41
5   Krishna   34    Chennai    Male      89

 

Let’s create a multi index on City and Gender columns.

 

df.set_index(['City', 'Gender'], inplace=True)

 

After executing the above statement, a multi index on the columns 'City' and 'Gender' is created on dataset.

                       Name  Age  Rating
City      Gender                       
Bangalore Male     Krishna   34      39
Hyderabad Female     Sailu   35      43
          Male        Joel   29      67
Chennai   Female     Chamu   35     100
Bangalore Male    Jitendra   52      41
Chennai   Male     Krishna   34      89

Let’s swap the outer index level City with the inner index level Gender by calling swaplevel method.

 

df = df.swaplevel()

 

After executing the above statement, dataset looks like below.

                       Name  Age  Rating
Gender City                            
Male   Bangalore   Krishna   34      39
Female Hyderabad     Sailu   35      43
Male   Hyderabad      Joel   29      67
Female Chennai       Chamu   35     100
Male   Bangalore  Jitendra   52      41
       Chennai     Krishna   34      89

As you observe above snippet, Outer most level is changed to Gender now.

 

Find the below working application.

 

swap_levels.py

import pandas as pd

# Create a sample DataFrame
data = {'Name': ['Krishna', 'Sailu', 'Joel', 'Chamu', 'Jitendra', "Krishna"],
        'Age': [34, 35, 29, 35, 52, 34],
        'City': ['Bangalore', 'Hyderabad', 'Hyderabad', 'Chennai', 'Bangalore', 'Chennai'],
        'Gender': ['Male', 'Female', 'Male', 'Female', 'Male', 'Male'],
        'Rating': [39, 43, 67, 100, 41, 89]}
df = pd.DataFrame(data)
print('Original DataFrame')
print(df)

df.set_index(['City', 'Gender'], inplace=True)
print('\nDataframe after setting the indexes\n', df)

df = df.swaplevel()
print('\nAfter swapping index levels City and Gender\n', df)

Output

Original DataFrame
       Name  Age       City  Gender  Rating
0   Krishna   34  Bangalore    Male      39
1     Sailu   35  Hyderabad  Female      43
2      Joel   29  Hyderabad    Male      67
3     Chamu   35    Chennai  Female     100
4  Jitendra   52  Bangalore    Male      41
5   Krishna   34    Chennai    Male      89

Dataframe after setting the indexes
                       Name  Age  Rating
City      Gender                       
Bangalore Male     Krishna   34      39
Hyderabad Female     Sailu   35      43
          Male        Joel   29      67
Chennai   Female     Chamu   35     100
Bangalore Male    Jitendra   52      41
Chennai   Male     Krishna   34      89

After swapping index levels City and Gender
                       Name  Age  Rating
Gender City                            
Male   Bangalore   Krishna   34      39
Female Hyderabad     Sailu   35      43
Male   Hyderabad      Joel   29      67
Female Chennai       Chamu   35     100
Male   Bangalore  Jitendra   52      41
       Chennai     Krishna   34      89

‘swaplevel()’ method will work perfectly fine when you have a multi index with two columns. But if you have a multi index with more than 2 columns, then you should explicitly specify the columns that you want to swap.

 

For example, I have a data set with the columns City, Gender and Age

                           Name  Rating
City      Gender Age                  
Bangalore Male   34    Krishna      39
Hyderabad Female 35      Sailu      43
          Male   29       Joel      67
Chennai   Female 35      Chamu     100
Bangalore Male   52   Jitendra      41
Chennai   Male   34    Krishna      89

Now I want to swap the levels Gender and Age levels. To do that I can specify the level labels explicitly.

 

df = df.swaplevel('Gender', 'Age')

 

Above snippet transforms the data set like below.

                           Name  Rating
City      Age Gender                  
Bangalore 34  Male     Krishna      39
Hyderabad 35  Female     Sailu      43
          29  Male        Joel      67
Chennai   35  Female     Chamu     100
Bangalore 52  Male    Jitendra      41
Chennai   34  Male     Krishna      89

You can even swap the indexes in a multi index by specifying their positions. For example, following snippet swap City and Gender indexes using index positions.

 

df = df.swaplevel(0, 2)

 

Find the below working application.

 

swap_levels_specify_labels.py

import pandas as pd

# Create a sample DataFrame
data = {'Name': ['Krishna', 'Sailu', 'Joel', 'Chamu', 'Jitendra', "Krishna"],
        'Age': [34, 35, 29, 35, 52, 34],
        'City': ['Bangalore', 'Hyderabad', 'Hyderabad', 'Chennai', 'Bangalore', 'Chennai'],
        'Gender': ['Male', 'Female', 'Male', 'Female', 'Male', 'Male'],
        'Rating': [39, 43, 67, 100, 41, 89]}
df = pd.DataFrame(data)
print('Original DataFrame')
print(df)

df.set_index(['City', 'Gender', 'Age'], inplace=True)
print('\nDataframe after setting the indexes\n', df)

df = df.swaplevel('Gender', 'Age')
print('\nAfter swapping index levels Gender and Age\n', df)

df = df.swaplevel(0, 2)
print('\nAfter swapping index levels City and Gender\n', df)

Output

Original DataFrame
       Name  Age       City  Gender  Rating
0   Krishna   34  Bangalore    Male      39
1     Sailu   35  Hyderabad  Female      43
2      Joel   29  Hyderabad    Male      67
3     Chamu   35    Chennai  Female     100
4  Jitendra   52  Bangalore    Male      41
5   Krishna   34    Chennai    Male      89

Dataframe after setting the indexes
                           Name  Rating
City      Gender Age                  
Bangalore Male   34    Krishna      39
Hyderabad Female 35      Sailu      43
          Male   29       Joel      67
Chennai   Female 35      Chamu     100
Bangalore Male   52   Jitendra      41
Chennai   Male   34    Krishna      89

After swapping index levels Gender and Age
                           Name  Rating
City      Age Gender                  
Bangalore 34  Male     Krishna      39
Hyderabad 35  Female     Sailu      43
          29  Male        Joel      67
Chennai   35  Female     Chamu     100
Bangalore 52  Male    Jitendra      41
Chennai   34  Male     Krishna      89

After swapping index levels City and Gender
                           Name  Rating
Gender Age City                       
Male   34  Bangalore   Krishna      39
Female 35  Hyderabad     Sailu      43
Male   29  Hyderabad      Joel      67
Female 35  Chennai       Chamu     100
Male   52  Bangalore  Jitendra      41
       34  Chennai     Krishna      89

 

Previous                                                 Next                                                 Home

How to extract the row from multi index data frame?

In this post, I am going to explain how to extract the row from a multi index data frame using ‘loc’ accessor.

Let’s use below data set to experiment with the examples.

               Sales       City
Year Quarter                  
2022 1          100  Bangalore
     3          150  Bangalore
2020 2          115  Bangalore
2021 3          120  Hyderabad
     1          180  Hyderabad
     2           90  Hyderabad
2020 1          130    Chennai
2022 2          160    Chennai

 

As you see above snippet, ‘Year’ and ‘Quarter’ are used as indexes.

 

Example 1: Get the 3rd quarter results of year 2022.

By supplying the multi index values as a tuple, we can extract the row details.

year_2022_quarter_3_results = df.loc[(2022, 3)]

 

 

Example 2: Extract only ‘Sales’ column for the 3rd quarter results of year 2022.

 

By specifying the list of columns that we are interested as second argument, we can extract the column values of our choice.

 

year_2022_quarter_3_sales = df.loc[(2022, 3), ['Sales']]

 

Find the below working application.

 

access_row.py

 

import pandas as pd

# Create a sample DataFrame
data = {'Year': [2022, 2022, 2020, 2021, 2021, 2021, 2020, 2022],
        'Quarter': [1, 3, 2, 3, 1, 2, 1, 2],
        'Sales': [100, 150, 115, 120, 180, 90, 130, 160],
        'City': ['Bangalore', 'Bangalore', 'Bangalore', 'Hyderabad', 'Hyderabad', 'Hyderabad', 'Chennai', 'Chennai']
        }
df = pd.DataFrame(data)
print('Original DataFrame\n', df)

# Set Year and Quarter as indexes
df.set_index(['Year', 'Quarter'], inplace=True)
print('\nAfter setting index columns Year and Quarter\n',df)

year_2022_quarter_3_results = df.loc[(2022, 3)]
print('\nyear_2022_quarter_3_results\n',year_2022_quarter_3_results)

# Extract Sales column only
year_2022_quarter_3_sales = df.loc[(2022, 3), ['Sales']]
print('\nyear_2022_quarter_3_sales\n',year_2022_quarter_3_sales)

 

Output

Original DataFrame
    Year  Quarter  Sales       City
0  2022        1    100  Bangalore
1  2022        3    150  Bangalore
2  2020        2    115  Bangalore
3  2021        3    120  Hyderabad
4  2021        1    180  Hyderabad
5  2021        2     90  Hyderabad
6  2020        1    130    Chennai
7  2022        2    160    Chennai

After setting index columns Year and Quarter
               Sales       City
Year Quarter                  
2022 1          100  Bangalore
     3          150  Bangalore
2020 2          115  Bangalore
2021 3          120  Hyderabad
     1          180  Hyderabad
     2           90  Hyderabad
2020 1          130    Chennai
2022 2          160    Chennai

year_2022_quarter_3_results
 Sales          150
City     Bangalore
Name: (2022, 3), dtype: object

year_2022_quarter_3_sales
 Sales    150
Name: (2022, 3), dtype: int64

 

 

Previous                                                 Next                                                 Home

Sunday, 7 April 2024

Copy InputStream to OutputStream in Java

In Java, copying data from an InputStream to an OutputStream is a common task, especially when dealing with file operations, network communications, or handling HTTP requests. In this blog post, we'll explore efficient methods to perform this operation, discussing best practices and potential pitfalls along the way.

 

Below are several scenarios in which copying an InputStream to an OutputStream is common in Java:

 

1.   Data Forwarding: In situations where you need to transfer data from one stream to another, such as redirecting the output of one program to serve as input for another.

2.   File Persistence: When dealing with an InputStream sourced from a network request or another origin, you may want to replicate its content into a FileOutputStream to persist the data into a file.

3.   Temporary Data Storage: Utilizing a ByteArrayOutputStream, you can duplicate a stream's content into memory temporarily, facilitating subsequent processing operations.

 

Approach 1: Using plain core java InputStream and OutputStream classes.

 

IOStreamUtil1.java

package com.sample.app.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class IOStreamUtil1 {

	private IOStreamUtil1() {
		// Restrict to create an object to this
	}

	public static final int DEFAULT_BUFFER_SIZE = 8192;

	public static long copy(InputStream inputStream, OutputStream outputStream, boolean closeOutputStream)
			throws IOException {
		return copy(inputStream, outputStream, closeOutputStream, new byte[DEFAULT_BUFFER_SIZE]);
	}

	public static long copy(InputStream inputStream, OutputStream outputStream, boolean closeOutputStream,
			byte[] buffer) throws IOException {

		if (inputStream == null) {
			throw new IllegalArgumentException("inputStream is null");
		}

		if (outputStream == null) {
			throw new IllegalArgumentException("outputStream is null");
		}

		try (InputStream in = inputStream) {
			long total = 0;

			int res = -1;

			while ((res = in.read(buffer)) != -1) {
				total += res;
				if (outputStream != null) {
					outputStream.write(buffer, 0, res);
				}
			}

			if (closeOutputStream) {
				outputStream.close();
			} else {
				outputStream.flush();
			}

			return total;
		}
	}
	
	public static void main(String[] args) throws IOException {
		// Create sample input and output streams
        ByteArrayInputStream inputStream = new ByteArrayInputStream("Hello, World!".getBytes());
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

        // Test the copy method
        long bytesCopied = copy(inputStream, outputStream, true);

        // Print the result
        System.out.println("Bytes copied: " + bytesCopied);
        System.out.println("Output stream content: " + outputStream.toString());
	}
}

 

Output

Bytes copied: 13
Output stream content: Hello, World!

Approach 2: Using InputStream#transferTo method.

 

public long transferTo(OutputStream out) throws IOException

This method is introduced in Java9. Reads all bytes from this input stream and writes the bytes to the given output stream in the order that they are read. On return, this input stream will be at end of stream. This method does not close either stream. If the total number of bytes transferred is greater than Long.MAX_VALUE, then Long.MAX_VALUE will be returned.

 


IOStreamUtil2.java

 

package com.sample.app.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class IOStreamUtil2 {

	public static long copy(InputStream inputStream, OutputStream outputStream) throws IOException {

		if (inputStream == null) {
			throw new IllegalArgumentException("inputStream is null");
		}

		if (outputStream == null) {
			throw new IllegalArgumentException("outputStream is null");
		}

		return inputStream.transferTo(outputStream);

	}

	public static void main(String[] args) throws IOException {
		// Create sample input and output streams
		ByteArrayInputStream inputStream = new ByteArrayInputStream("Hello, World!".getBytes());
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

		// Test the copy method
		long bytesCopied = copy(inputStream, outputStream);

		// Print the result
		System.out.println("Bytes copied: " + bytesCopied);
		System.out.println("Output stream content: " + outputStream.toString());
	}
}

Approach 3: Using Apache commons IOUtils.copy method.

 

Apache Commons IO library provides utility methods for working with streams, including copying streams efficiently. Using this library simplifies the code and makes it more readable.

 

public static int copy(final InputStream inputStream, final OutputStream outputStream) throws IOException

Copies bytes from an InputStream to an OutputStream. Large streams (over 2GB) will return a bytes copied value of -1 after the copy has completed since the correct number of bytes cannot be returned as an int. For large streams use the copyLarge(InputStream, OutputStream) method.

 

IOStreamUtil3.java

package com.sample.app.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.commons.io.IOUtils;

public class IOStreamUtil2 {

	public static int copy(InputStream inputStream, OutputStream outputStream) throws IOException {

		if (inputStream == null) {
			throw new IllegalArgumentException("inputStream is null");
		}

		if (outputStream == null) {
			throw new IllegalArgumentException("outputStream is null");
		}

		int noOfBytesopied = IOUtils.copy(inputStream, outputStream);
		return noOfBytesopied;
	}

	public static void main(String[] args) throws IOException {
		// Create sample input and output streams
		ByteArrayInputStream inputStream = new ByteArrayInputStream("Hello, World!".getBytes());
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

		// Test the copy method
		long bytesCopied = copy(inputStream, outputStream);

		// Print the result
		System.out.println("Bytes copied: " + bytesCopied);
		System.out.println("Output stream content: " + outputStream.toString());
	}
}

Approach 4: Using IOUtils.copyLarge method.

public static long copyLarge(final InputStream inputStream, final OutputStream outputStream) throws IOException

public static long copyLarge(final InputStream inputStream, final OutputStream outputStream, final byte[] buffer)

Copies bytes from a large (over 2GB) InputStream to an OutputStream This method buffers the input internally, so there is no need to use a BufferedInputStream. Default buffer size is 8192 bytes.

 

IOStreamUtil4.java

package com.sample.app.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.commons.io.IOUtils;

public class IOStreamUtil3 {

	public static long copy(InputStream inputStream, OutputStream outputStream) throws IOException {

		if (inputStream == null) {
			throw new IllegalArgumentException("inputStream is null");
		}

		if (outputStream == null) {
			throw new IllegalArgumentException("outputStream is null");
		}

		long noOfBytesopied = IOUtils.copyLarge(inputStream, outputStream);
		return noOfBytesopied;
	}

	public static void main(String[] args) throws IOException {
		// Create sample input and output streams
		ByteArrayInputStream inputStream = new ByteArrayInputStream("Hello, World!".getBytes());
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

		// Test the copy method
		long bytesCopied = copy(inputStream, outputStream);

		// Print the result
		System.out.println("Bytes copied: " + bytesCopied);
		System.out.println("Output stream content: " + outputStream.toString());
	}
}

Approach 5: Using Java NIO

Java NIO offers a non-blocking I/O API that can also be used for efficient stream copying. This approach is particularly useful when dealing with large files or when performance is critical.

 

IOStreamUtil5.java

package com.sample.app.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;

public class IOStreamUtil4 {

	public static void copy(InputStream inputStream, OutputStream outputStream, boolean closeOutputStream)
			throws IOException {

		if (inputStream == null) {
			throw new IllegalArgumentException("inputStream is null");
		}

		if (outputStream == null) {
			throw new IllegalArgumentException("outputStream is null");
		}

		try (InputStream inp = inputStream;
				ReadableByteChannel inChannel = Channels.newChannel(inp);
				WritableByteChannel outChannel = Channels.newChannel(outputStream)) {
			ByteBuffer buffer = ByteBuffer.allocateDirect(8192); // 8KB buffer size
			while (inChannel.read(buffer) != -1) {
				buffer.flip();
				outChannel.write(buffer);
				buffer.clear();
			}
		}

		if (closeOutputStream) {
			outputStream.close();
		} else {
			outputStream.flush();
		}

	}

	public static void main(String[] args) throws IOException {
		// Create sample input and output streams
		ByteArrayInputStream inputStream = new ByteArrayInputStream("Hello, World!".getBytes());
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

		// Test the copy method
		copy(inputStream, outputStream, true);

		System.out.println("Output stream content: " + outputStream.toString());
	}
}

Copying data from an InputStream to an OutputStream is a fundamental operation in Java programming. By using buffered streams, leveraging third-party libraries like Apache Commons IO, or utilizing the Java NIO package, you can perform this task efficiently and effectively. Consider your specific requirements, such as performance, resource usage, and code readability, when choosing the appropriate method for copying streams in your Java applications.


 

You may like

file and stream programs in Java

Write InputStream to a file in Java

File separator, separatorChar, pathSeparator, pathSeparatorChar in Java

Implement an Output stream that writes the data to two output streams

Check whether directory can be accessed and has read and write privileges in Java

Get the hash or message digest of a file in Java