【问题标题】:How do I create a list from a data frame, containing each value of string column, multiplied by a second column? [duplicate]如何从数据框中创建一个列表,其中包含字符串列的每个值乘以第二列? [复制]
【发布时间】:2019-08-02 23:20:03
【问题描述】:

提供示例后,问题会变得更加清晰。 我有一个包含两列的数据框,一列类型为字符串,一列类型为整数:

Col1   Col2
-------------
str1    2
str2    4
str3    1

现在我需要一个列表,其中包含 Col1 中的字符串乘以 Col2 中的数字,即['str1', 'str1', 'str2', 'str2', 'str2', 'str2', 'str3']

最有效的方法是什么?

【问题讨论】:

  • np.repeat(df['Col1'], df['Col2']).
  • 哇,真快。就这样,谢谢!

标签: python pandas list dataframe


【解决方案1】:
import numpy as np
np.repeat(df.Col1.values, df.Col2.values)

输出:

array(['str1', 'str1', 'str2', 'str2', 'str2', 'str2', 'str3'])

【讨论】:

    猜你喜欢
    • 2022-07-20
    • 2022-09-23
    • 1970-01-01
    • 2020-12-28
    • 2022-11-18
    • 2022-01-07
    • 1970-01-01
    • 1970-01-01
    • 2021-07-10
    相关资源
    最近更新 更多