Home > Back-end >  Convert data resulted a function into data frame
Convert data resulted a function into data frame

Time:07-27

I have run a function code on python to get output elevation using a code as given below. But I would like to convert the results into a data frame. depth() #function

Results: 0 49 2
         1 50 2.5
         2 52 3
         3 53 3.5
         4 54 4
         ......
         .......
        100 102 9

I am facing problems to turn these results into a data frame. I used following codes, but didn't work.

  df = pd.DataFrame(columns = ['id', 'Z', 'water level'])
    df = df.apply(water_depth())
    
    print(df)

CodePudding user response:

IIUC, you can try:

import pandas as pd
from io import StringIO

data = StringIO("""0 49 2
1 50 2.5
2 52 3
3 53 3.5
4 54 4
100 102 9
""")

df = pd.read_csv(data, sep=' ', header=None)
df.columns = ['id', 'Z', 'water level']
print(df)

Output:

    id    Z  water level
0    0   49          2.0
1    1   50          2.5
2    2   52          3.0
3    3   53          3.5
4    4   54          4.0
5  100  102          9.0

When you have the data saved in a file.csv, you can replace data with 'file.csv'.

CodePudding user response:

The way I'd do it:

dictionary = {
  'water_level':[x/10 for x in range(20,91,5)], #example
  'Z':[] # generate values of z
  'id':[] # generate values of id
}

If you have some special function to generate the values, just create three lists and then create the dictionary. After that:

pd.DataFrame(dictionary)
  • Related