简体   繁体   中英

create a pandas data frame from several lists

My function outputs a list, for instance when I type:

My_function('TV', 'TV_Screen')

it outputs the following:

['TV', 1, 'TV_Screen', 0.04, 'True']

Now, my TV is made of several parts, such as speaker, transformer, etc., I can keep running my function for each part, and for instance change 'TV_Screen' for 'TV_Speaker', or 'TV_transformer', etc.

The alternative is to create a list with all the part, such as:

TV_parts = ['TV_Screen', 'TV_Speaker', 'TV_transformer']

What I am trying to get is a pandas data frame with 5 columns (because my function outputs 5 variables, see above the section "it outputs the following:") and in this case 3 rows (one of each for 'TV_Screen', 'TV_Speaker', and 'TV_transformer'). Basically, I want the following to be in a data frame:

['TV', 1, 'TV_Screen', 0.04, 'True']
['TV', 9, 'TV_Speaker', 0.56, 'True']
['TV', 3, 'TV_transformer', 0.80, 'False']

I know I need a for loop somewhere, but I am not sure how to create this data frame. Could you please help? (I can change the output of my function to be a pd.Series or something else that would work better).

Thanks!

You can do it like this:

def My_function(part):
    # prepare result
    result = ['TV', 1, part, 0.04, 'True'] # for testing 
    return result

TV_parts = ['TV_Screen', 'TV_Speaker', 'TV_transformer']
df = pd.DataFrame([My_function(part) for part in TV_parts])

>>> df

    0  1               2     3     4
0  TV  1       TV_Screen  0.04  True
1  TV  1      TV_Speaker  0.04  True
2  TV  1  TV_transformer  0.04  True

If you have many arrays, it may be worth converting them into a numpy matrix first and then converting them into a dataframe.

import pandas as pd
import numpy as np

a = ['TV', 1, 'TV_Screen', 0.04, 'True']
b = ['TV', 9, 'TV_Speaker', 0.56, 'True']
c = ['TV', 3, 'TV_transformer', 0.80, 'False']

matrix = np.matrix([a,b,c])

df = pd.DataFrame(data=matrix)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM