'"columns must have matching element counts" while performing explode in pandas
I'm performing explode on 3 columns in a dataframe, all the 3 columns have the same number of elements. But while performing the explode operation, the code runs in a error
columns must have matching element counts
Below is the code snippet I'm trying to perform.
list1 = primary_secondary[['Column_x', 'Column_y']].replace('', np.nan).stack().groupby(level=0).apply(list)
list2 = primary_secondary[['Column_a', 'Column_b']].replace('', np.nan).stack().groupby(level=0).apply(list)
list3 = primary_secondary[['Column_c', 'Column_d']].replace('', np.nan).stack().groupby(level=0).apply(list)
df = df.assign(Combination_1=list1.fillna(''), Combination_2=list2.fillna(''),Combination_3=list3.fillna('') ).explode(['Combination_1', 'Combination_2', 'Combination_3'])
The operation I intend to perform is, combine columns column_x, column_y into a new column Combination_1, and that should be performed in the following manner.
I want to merge 2 columns of the same dataframe, and add a duplicate row using the same values as it has in the other columns
consider the following dataframe:
| Column A | Column B | Column C |
|---|---|---|
| ABC | '' | 1 |
| GHI | XYZ | 2 |
| '' | PQR | 3 |
| '' | '' | 4 |
The conditions are:
- If the Column A has a alphanumeric value and the Column B has a Nan value or a '' (empty string) -> the Result column should only consider the value from Number-first
- If the Column A has a Nan or '' (empty string) value and the Column B has a alphanumeric value -> the Result column should only consider the value from Number-second
- If the values from both the columns are alphanumeric the result column should duplicate itself where the first value should be Column A and the second value should be Column B
- If both the Columns have Nan or empty string values, the result should consist of a '' (empty string) value
Following would be the output for the above dataframe:
| Column A | Column B | Column C | Result |
|---|---|---|---|
| ABC | '' | 1 | ABC |
| GHI | XYZ | 2 | GHI |
| GHI | XYZ | 2 | XYZ |
| '' | PQR | 3 | PQR |
| '' | '' | 4 | '' |
I have been unsuccessful in making it work
Thanks a lot in advance for your help !
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
