无法解压缩的值太多- Pandas DataFrame

xlpyo6sf  于 2023-06-20  发布在  其他
关注(0)|答案(2)|浏览(123)

我有一个数据框架,我想应用一个函数,该函数接受一个值,并将给予两个值作为结果。我使用.apply(get_data).transpose().values将结果放到dataframe。当数据框架中只有两行但不能处理超过两行时,它就可以工作。我得到了“Too many values to unpack(expected 2)”错误。

oil_df = pd.DataFrame({
    "Oils":["Oil 1","Oil 2","Oil 3"], 
    "Price":["","",""], 
    "Unit":["","",""]})
def get_data(oil):
    if oil == "Oil 1":
        price = 20
        unit = 50
    if oil == "Oil 2":
        price = 30
        unit = 75
    if oil == "Oil 3":
        price = 40
        unit = 100
    return(price, unit)
oil_df["Price"], oil_df["Unit"] = oil_df["Oils"].apply(get_data).transpose().values

一开始,我找不到应用函数的方法,所以我把函数分成两部分,然后逐个应用,但花的时间和预期的一样长。我是在this answer的帮助下找到这个方法的。axis=1, result_type='expand给了我“get_data()got an unexpected keyword argument 'axis'”错误,所以删除了那部分。我愿意接受任何建议,使这项工作或其他方式将此功能应用到dataframe。谢谢你!

cyvaqqii

cyvaqqii1#

不知道你真正想实现的是什么,但是你正在转置数据,所以你返回的数组有3个元组(对于oil1,2和3),所以它有太多的值要解包。
如果您的意图是填充第二列和第三列,那么您希望返回一个包含2列的数据框架(即每行一个系列),然后将其用作数据框架的2列的输入

import pandas as pd

oil_df = pd.DataFrame({
    "Oils":["Oil 1","Oil 2","Oil 3"], 
    "Price":["","",""], 
    "Unit":["","",""]})

def get_data(oil):
    if oil == "Oil 1":
        price = 20
        unit = 50
    if oil == "Oil 2":
        price = 30
        unit = 75
    if oil == "Oil 3":
        price = 40
        unit = 100
    return pd.Series([price, unit])

oil_df[['Price', 'Unit']] = oil_df["Oils"].apply(get_data)

oil_df

退货

Oils    Price   Unit
0   Oil 1   20  50
1   Oil 2   30  75
2   Oil 3   40  100

在这种情况下

oil_df["Oils"].apply(get_data)

退货

0   1
0   20  50
1   30  75
2   40  100

并将其分配给oil_df[['Price', 'Unit']]合并数据

mo49yndu

mo49yndu2#

尝试locnp.select

for column, values in [('Price', [20, 30, 40]), ('Unit', [50, 75, 100])]:
    # loc
    # oil_df.loc[oil_df['Oils'].isin(['Oil 1', 'Oil 2', 'Oil 3']), column] = values
    # np.select
    oil_df[column] = np.select(condlist=[oil_df['Oils'] == f'Oil {i}' for i in range(1, 4)], choicelist=values)

输出

Oils Price Unit
0  Oil 1    20   50
1  Oil 2    30   75
2  Oil 3    40  100

相关问题