python-3.x 基于Pandas中已有列的除法运算创建列表型新列

iovurdzv  于 2023-01-10  发布在  Python
关注(0)|答案(2)|浏览(96)

我有一个数据框

df = pd.DataFrame([["X",62,5],["Y",16,3],["Z",27,4]],columns=["id","total","days"])
id total days
X   62    5
Y   16    3
Z   27    4

将 * total * column除以 * days * column并创建一个新列 * plan *,这是一个列表,其中元素的数量=除数,元素的值=商,如果有任何提示,则从负索引中增加这些值。

    • 预期产出:**

一个二个一个一个
如何在Pandas身上做到呢?

wdebmtf2

wdebmtf21#

您可以使用自定义函数:

def split(t, d):
    # get floor division and remainder
    x, r = divmod(t, d)
    # assign divider or divider + 1
    # depending on the number of remainders
    return [x]*(d-r)+[x+1]*r

df['plan'] = [split(t, d) for t, d in zip(df['total'], df['days'])]

输出:

id  total  days                  plan
0  X     62     5  [12, 12, 12, 13, 13]
1  Y     16     3             [5, 5, 6]
2  Z     27     4          [6, 7, 7, 7]
b1zrtrql

b1zrtrql2#

然而,这可以是另一种将costure函数与lambda配合使用的方法。

def create_plan(plan, days, remainder):
    return [plan]*days if remainder == 0 else [plan]*(days-remainder)+[plan+1]*remainder

df = pd.DataFrame([["X",62,5],["Y",16,3],["Z",27,4]],columns=["id","total","days"])

# Create plan column    
df["plan"] = df["total"] // df["days"]

# Create column for remainder
df["remainder"] = df["total"] % df["days"]

# Apply function to create final plan
df["plan"] = df.apply(lambda x: create_plan(x["plan"], x["days"], x["remainder"]), axis=1)

# Drop remainder column
df.drop("remainder", axis=1, inplace=True)
print(df)

输出:

id  total  days                  plan
0  X     62     5  [12, 12, 12, 13, 13]
1  Y     16     3             [5, 5, 6]
2  Z     27     4          [6, 7, 7, 7]

相关问题