I want to make a dataframe from all outputs from a python function. So I want to create a dataset as df. Any ideas?
import pandas as pd
def test(input):
kl = len(input)
return kl
test("kilo")
test("pound")
# initialize list of lists
data = [[4], [5]]
# Create the pandas DataFrame
df = pd.DataFrame(data, columns = ["Name"])
CodePudding user response:
Assuming this input and function:
words = [['abc', 'd'], ['efgh', '']]
def test(input):
kl = len(input)
return kl
You can create the DataFrame:
df = pd.DataFrame(words)
0 1
0 abc d
1 efgh
then applymap
your function (Warning: applymap
is slow, in this particular case (getting the length), there as much faster vectorial methods):
df2 = df.applymap(test)
0 1
0 3 1
1 4 0
Or run your function in python before creating the DataFrame:
df = pd.DataFrame([[test(x) for x in l] for l in words])
0 1
0 3 1
1 4 0
CodePudding user response:
A related approach would be to repeatedly call your function to make a list and then form the dataframe from it:
import pandas as pd words = ['kilo', 'pound', 'ton'] def test(input): kl = len(input) return kl data = [] # create empty list for entry in words: data.append(test(entry))
df = pd.DataFrame(data, columns = ['names'])