1

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

3 Answers 3

3

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']
Sign up to request clarification or add additional context in comments.

18 Comments

I have tried this code, but I got this error: ValueError: Length mismatch: Expected axis has 4 elements, new values have 3 elements
@NgrWisnu How about with df = pd.DataFrame(data).set_axis(['mean', 'total', 'power'], axis=1).T.assign(label=[f'data{i}' for i in range(1, 5)])
I got another error: ValueError: Length mismatch: Expected axis has 10 elements, new values have 3 elements is the error from the set_axis?
@NgrWisnu How about df = pd.DataFrame(data).T.set_axis(['mean', 'total', 'power', 'label'], axis=1).assign(label=[f'data{i}' for i in range(1, 5)])
ValueError: Length of values (4) does not match length of index (10)
|
1

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()]
})```

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.