'Efficient way to concatenate dataframe with its columns reversed
One fairly recurring pattern I have is creating a dataframe that combines another dataframe with its columns reversed. Here's a small example:
import pandas as pd
df = pd.DataFrame({"a": range(5), "b": range(6, 1, -1)})
combined = pd.concat([df, df.rename(columns={"a": "b", "b": "a"})], ignore_index=True)
Is there a more efficient approach to achieving this operation (esp. with many, many rows)?
Solution 1:[1]
You can use the underlying numpy array and vstack on the array and its reversed version, then generate a new DataFrame:
import numpy as np
a = df.to_numpy()
pd.DataFrame(np.vstack([a, a[:, ::-1]]), columns=df.columns)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
