Ngr Wisnu
Ngr Wisnu

Reputation: 57

How to create a dynamic DataFrame to export multiple data to excel with Pandas?

I have a function that return some values:

def sigInput(audio):
    ...
    ...
    ...
    return [mean, total, power]

data1 = sigInput('sound1.wav')
data2 = sigInput('sound2.wav')
data3 = sigInput('sound3.wav')
data4 = sigInput('sound4.wav')


df = pd.DataFrame({
    'mean': [data1[0], data2[0], data3[0], data4[0]],
    'total': [data1[1], data2[1], data3[1], data4[1]],
    'power': [data1[2], data2[2], data3[2], data4[2]],
    'label': ['data1', 'data2', 'data3', 'data4']
})

df.to_excel('expData.xlsx')

Based on the code above, data1, data2, data3, and data4 will have three values according to what the function returns. My target is I want to export these data to excel using pandas.

If I have more than four data, maybe 10 or 20 data, then I have to write the DataFrame manually.

My question is how to make the contents in the pd.DataFrame more dynamic if it has a lot of data?

Thank you for the help

Upvotes: 1

Views: 549

Answers (3)

U13-Forward
U13-Forward

Reputation: 71580

Try something like:

data = [sigInput(f'sound{i}.wav') for i in range(1, 5)]
df = pd.DataFrame(data).assign(label=[f'data{i}' for i in range(1, 5)])
df.columns = ['mean', 'total', 'power', 'label']

Upvotes: 3

Aditya
Aditya

Reputation: 1377

You can create a dictionary containing the label name and the data and use it while creating the dataframe like this:

data_dict = {"data1":data1,"data2":data2,"data3":data3,"data4":data4,"data5":data5}

df = pd.DataFrame({
    'mean': [x[0] for x in data_dict.values()],
    'total': [x[1] for x in data_dict.values()],
    'power': [x[2] for x in data_dict.values()],
    'label': [x for x in data_dict.keys()]
})```

Upvotes: 1

Kaiwalya Patil
Kaiwalya Patil

Reputation: 62

Write a for loop to create that list of list and then pass it into the dictionary.

s = [data1,data2,data3]
for i in range(len(s)):
    d = s[i]
    for j in range(0,4):
        d = d[j]

You can append the last d in a list or so and then pass on

Upvotes: 0

Related Questions