English 中文(简体)
太多的未包装价值——Pandas DataFrame
原标题:Too many values to unpack - Pandas DataFrame

I have a dataframe that I want to apply a function that take one value and will give two values as a result. I used .apply(get_data).transpose().values to put the results to the dataframe. It worked when I had only two rows in the dataframe but didn t worked with more than two rows. I got the "Too many values to unpack (expected 2)" error.

 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

At first, I couldn t find a way to apply the function, so I divided the function to two pieces and applied them one by one, but it took so much longer as expected. I found this way with the help of this answer. axis=1, result_type= expand is giving me "get_data() got an unexpected keyword argument axis " error, so removed that part. I m open to any suggestions to make this work or another way to apply this function to the dataframe. Thank you!

问题回答

不知道你真心想做到这一点,但你正在转换数据,因此,你返回的阵列有3个 t子(石油1、2和3),因此其价值太多,无法包装。

如果你打算填入第二栏和第三栏,那么你就希望回到一个数据组,即每行一个系列,然后将其用作对数据组第二栏的投入。

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[[价格,单位]]

Try loc or np.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




相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签