【问题标题】:Add a column to a dataset whose values ​are filled by groups向数据集添加一列,其值按组填充
【发布时间】:2019-08-02 03:50:45
【问题描述】:

我有一个数据集,其中包含以下列:周、商店、商品编号和价格。我还有一个唯一编号数组,它们等于项目编号,但顺序不同。 我想根据这些唯一数字向该数据集添加新列。首先,我需要按周对这个数据集进行分组并购物。然后在特定的一周和特定的商店中,我需要找到一个等于新列名的项目编号(唯一编号数组中的元素)。如果没有这样的字段,则填写 null。 然后我应该用这个项目编号的价格填写特定一周和特定商店的所有字段。

这是我尝试过的一些代码,但运行速度很慢,因为行数非常大。

#real dataset
data2
weeks = data2['Week'].unique()

for k in range(len(Unique_number)):
    for i in range(len(weeks)):
        temp_array = data2.loc[data2["Week"] == weeks[i]]
        stores = temp_array['Shop'].unique()
        for j in range(len(stores)):
            temp_array2 = temp_array.loc[data2["Shop"] == stores[j]]
            price = temp_array2.loc[temp_array2["Item number"] == Unique_number[k], "Price"]
            if (price.empty):
                price = 0 
            else:
                price = price.values[0]
            data2.loc[(data2["Week"] == weeks[i]) & (data2["Shop"] == stores[j]),Unique_number[k]] = price

我想要这样的东西

Unique_numbers = [0,1,2,3]

dataframe before
week; shop; Item number; price
1     1     0            2
1     2     1            3
2     1     3            4
2     1     2            5
3     4     1            6
3     1     2            7



dataframe after
week; shop; Item number; price; 0; 1; 2; 3
1     1     0            2      2  0  0  0
1     2     1            3      0  3  0  0  
2     1     3            4      0  0  5  4
2     1     2            5      0  0  5  4
3     4     1            6      0  6  0  0
3     1     2            7      0  0  7  0

【问题讨论】:

  • 恐怕我根本不理解您的输出。输入值到输出值的映射是什么? 2 1 3 42 1 2 5 如何映射到相同的输出 0 0 5 4

标签: python pandas numpy


【解决方案1】:

设置

u = df['Item number'].to_numpy()
w = np.asarray(Unique_numbers)
g = [df.week, df.shop]

在这里使用一些广播比较(假设您的所有price 值都大于0)。


pd.DataFrame(
  np.equal.outer(u, w) * df['price'].to_numpy()[:, None]).groupby(g).transform('max')

   0  1  2  3
0  2  0  0  0
1  0  3  0  0
2  0  0  5  4
3  0  0  5  4
4  0  6  0  0
5  0  0  7  0

【讨论】:

    【解决方案2】:

    这是pivotmerge 的组合:

    df.merge(df.pivot_table(index=['week', 'shop'], 
                           columns='Item number', 
                           values='price',
                           fill_value=0)
               .reindex(Unique_numbers, axis=1),
             left_on=['week', 'shop'],
             right_index=True,
             how='left'
            )
    

    输出:

       week  shop  Item number  price  0  1  2  3
    0     1     1            0      2  2  0  0  0
    1     1     2            1      3  0  3  0  0
    2     2     1            3      4  0  0  5  4
    3     2     1            2      5  0  0  5  4
    4     3     4            1      6  0  6  0  0
    5     3     1            2      7  0  0  7  0
    

    【讨论】:

    • @user3483203 谢谢克里斯,更新了我的答案。
    猜你喜欢
    • 1970-01-01
    • 2013-12-13
    • 2019-11-21
    • 2019-06-06
    • 2011-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-09
    相关资源
    最近更新 更多