Description:
I have 4 lists that I would like to explode in the following order temps
, volts
, powers
and freqs
.
import pandas as pd
temps = [-20,60]
volts = [6.3, 7.4]
powers = [float(p) for p in range(15,35,5)]
freqs = [float(f) for f in range(100,120,10)]
Expected output:
temps | volts | powers | freqs |
---|---|---|---|
-20 | 6.3 | 15 | 100 |
-20 | 6.3 | 15 | 110 |
-20 | 6.3 | 20 | 100 |
-20 | 6.3 | 20 | 110 |
-20 | 6.3 | 25 | 100 |
-20 | 6.3 | 25 | 110 |
-20 | 6.3 | 30 | 100 |
-20 | 6.3 | 30 | 110 |
-20 | 7.4 | 15 | 100 |
-20 | 7.4 | 15 | 110 |
-20 | 7.4 | 20 | 100 |
-20 | 7.4 | 20 | 110 |
-20 | 7.4 | 25 | 100 |
-20 | 7.4 | 25 | 110 |
-20 | 7.4 | 30 | 100 |
-20 | 7.4 | 30 | 110 |
60 | 6.3 | 15 | 100 |
60 | 6.3 | 15 | 110 |
60 | 6.3 | 20 | 100 |
60 | 6.3 | 20 | 110 |
60 | 6.3 | 25 | 100 |
60 | 6.3 | 25 | 110 |
60 | 6.3 | 30 | 100 |
60 | 6.3 | 30 | 110 |
60 | 7.4 | 15 | 100 |
60 | 7.4 | 15 | 110 |
60 | 7.4 | 20 | 100 |
60 | 7.4 | 20 | 110 |
60 | 7.4 | 25 | 100 |
60 | 7.4 | 25 | 110 |
60 | 7.4 | 30 | 100 |
60 | 7.4 | 30 | 110 |
Need help with the following code:
df = pd.DataFrame({"temps":[temps], "volts": [volts], "powers": [powers], "freqs":[freqs]})
df.explode(df.columns.to_list())
Current error:
ValueError: columns must have matching element counts
Dirty work around the issue:
I’ve wrote a code that could do it for time being, however in the future I would need to add even more test cases, so this code will be causing issues:
nested_list = lambda N,data: [data for n in range(len(N))]
df = pd.DataFrame({"temps":temps, "volts": nested_list(temps,volts)})
df = df.explode(['volts'])
df["powers"] = nested_list(df.temps,powers)
df = df.explode(['powers'])
df["freqs"] = nested_list(df.temps,freqs)
df = df.explode(['freqs']).reset_index(drop=True)