从python中函数的输出创建一个数据帧



我想从一个python函数的所有输出中生成一个数据帧。我想创建一个数据集df。什么好主意吗?

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"])

假设以下输入和功能:

words = [['abc', 'd'], ['efgh', '']]
def test(input):
kl = len(input)
return kl

你可以创建DataFrame:

df = pd.DataFrame(words)
0  1
0   abc  d
1  efgh   

然后applymap你的函数(警告:applymap很慢,在这种特殊情况下(获得长度),有更快的矢量方法):

df2 = df.applymap(test)
0  1
0  3  1
1  4  0

或者在创建DataFrame之前用python运行你的函数:

df = pd.DataFrame([[test(x) for x in l] for l in words])
0  1
0  3  1
1  4  0

一种相关的方法是反复调用函数来生成列表,然后从中形成数据框架:

import pandas as pdWords = ['kilo', 'pound', 'ton']def测试(输入):Kl = len(输入)返回吉隆坡Data =[] #创建空列表以文字输入:data.append(测试(条目))

df = pd。DataFrame(data, columns = ['names'])

最新更新