从值和值计数的数据集构造一个列表

2024-04-25 18:09:28 发布

您现在位置:Python中文网/ 问答频道 /正文

要将数据Score扩展到基于CountScores列表中,pandasnumpy中是否有比下面更好的方法?你知道吗

import pandas as pd
import numpy as np

data = {
    "Count": [1, 3, 2],
    "Score": [2, 5, 8]
}

df = pd.DataFrame(data)

scores = []

for c, s in zip(df['Count'], df['Score']):
    for i in range(0, c):
        scores.append(s)

print(scores)

预期产量:

[2, 5, 5, 5, 8, 8]


Tags: 数据inimportnumpypandasdf列表for
1条回答
网友
1楼 · 发布于 2024-04-25 18:09:28

IIUC,您可以使用^{}

df['Score'].repeat(df['Count']).tolist()

^{}

np.repeat(df['Score'],df['Count']).tolist()

^{}

df.loc[df.index.repeat(df['Count']),'Score'].tolist()

[2, 5, 5, 5, 8, 8]

相关问题 更多 >