gpt4 book ai didi

python - 我有一个返回系列的函数。我希望将此函数作为新列应用到另一个数据框

转载 作者:行者123 更新时间:2023-12-04 08:28:01 24 4
gpt4 key购买 nike

我有一个返回系列的函数。我希望将一个函数应用到数据帧中,并使该函数不覆盖现有列,而是使用系列索引中的列名创建新列。

#SITUATION:
##Existing 1 dimensional dataframe. Could be series too:
df = pd.DataFrame({'Fruit' : ['Apple','Banana','Grapes','Oranges']})

##The function I'm trying to apply to each fruit:
def my_func(fruit):
series = get weight,taste, shape, price etc using an API (which is a pandas series)
return series

#DESIRED OUTPUT

Fruit Weight Taste Shape Price
Apple 6 Tarty Oval $2
Banana 5 Sweet Long $1
Grapes 3 Sweet Round $4
Oranges 5 Acidic Round $2

#CURRENT OUTPUT (Only one column with whole series embedded inside the element)
FRUIT
Weight:6, Taste:Tary, Shape:Oval, Price:$2
Weight:5, Taste:Sweet, Shape:Long, Price:$1
Weight:3, Taste:Sweet, Shape:Round, Price:$4
Weight:5, Taste:Acidic,, Shape:Round, Price:$2

我试过使用 applymap 并尝试拆开但没有用。任何帮助表示赞赏

最佳答案

您可以执行以下操作:

df.set_index('Fruit', drop=False, inplace=True)
df = pd.concat([my_func(fruit) for fruit in df.Fruit],
axis='columns').T.set_index(df.Fruit)
使用您的数据帧 df
api = {
'Apple': pd.Series({'Weight': 6, 'Taste': 'Tary', 'Shape': 'Oval', 'Price': '$2'}),
'Banana': pd.Series({'Weight': 5, 'Taste': 'Sweet', 'Shape': 'Long', 'Price': '$1'}),
'Grapes': pd.Series({'Weight': 3, 'Taste': 'Sweet', 'Shape': 'Round', 'Price': '$4'}),
'Oranges': pd.Series({'Weight': 5, 'Taste': 'Acidic', 'Shape': 'Round', 'Price': '$2'})
}

def my_func(fruit):
return api[fruit]
结果是:
        Weight   Taste  Shape Price
Fruit
Apple 6 Tary Oval $2
Banana 5 Sweet Long $1
Grapes 3 Sweet Round $4
Oranges 5 Acidic Round $2
如果由于某种原因你必须使用 applymap那么你可以做这样的事情:
num_fruits = df.shape[0]
df.set_index('Fruit', drop=False, inplace=True)
df = df.applymap(my_func).explode('Fruit')
df.rename(columns={'Fruit': 'Values'}, inplace=True)
df['Columns'] = ['Weight', 'Taste', 'Shape', 'Price'] * num_fruits
df = df.pivot(columns=['Columns'], values=['Values'])
df = df.droplevel(0, axis='columns')
df.columns.name = None

关于python - 我有一个返回系列的函数。我希望将此函数作为新列应用到另一个数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65164119/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com