【问题标题】:Python Pandas Repeat a value x amount of times according to x valuePython Pandas 根据 x 值重复一个值 x 次
【发布时间】:2022-01-05 19:15:10
【问题描述】:

我是 Python 和 Pandas 的新手,我正在尝试使用一个简单的函数,该函数将根据相邻值重复 x 次值。

例如:

我想取第一列(重量)并根据它旁边的数量(轮子)将其添加到新列中。因此,该列将具有 1.5 27x,而不是紧随其后将具有 2.4 177x,并对显示的所有值重复此操作。有谁知道一个简单的方法来做到这一点?

【问题讨论】:

  • 只需使用numpynp.repeat(df.Weight.to_numpy(), df.Wheels)。然后,如果您真的需要,可以将该数组放入 Series 或 DataFrame 中。由于这个新列的形状与原始 DataFrame 完全不同,因此将重复数据存储在与原始数据相同的对象中是没有意义的。
  • 请查看How to make good pandas examplesedit 以将您的示例输入和预期输出作为文本而不是图像或链接包含在minimal reproducible example

标签: python pandas csv


【解决方案1】:

使用Series.repeat:

out = df['Weight'].repeat(df['Wheels'])
print(out)

# Output
0    1.5
0    1.5
1    2.4
1    2.4
1    2.4
Name: Weight, dtype: float64

设置:

df = pd.DataFrame({'Weight': [1.5, 2.4], 'Wheels': [2, 3]})
print(df)

# Output
   Weight  Wheels
0     1.5       2
1     2.4       3

【讨论】:

  • 我看到你喜欢Series.repeat ;) +1
  • 当然可以。我今天看到了这种技术:)
【解决方案2】:

假设您有一个名为 df 的 pandas 数据框。

import numpy as np
np.repeat(df['weigth'], df['wheels'])

【讨论】:

    猜你喜欢
    • 2017-10-27
    • 2017-09-23
    • 2021-12-09
    • 1970-01-01
    • 2014-12-27
    • 2020-07-28
    • 1970-01-01
    • 2017-09-16
    • 1970-01-01
    相关资源
    最近更新 更多