我有一个数据框:
function updateTotal() {
let total = 0;
let arr = [];
const items = document.querySelectorAll(".prodItem");
for (i = 0; i < items.length; i++) {
priceAmount = items[i].querySelectorAll(".prodPrice")[0];
productQuantity = items[i].querySelectorAll(".num")[0];
const quantity = productQuantity.value;
const priceContent = priceAmount.innerText;
const price = priceContent.replace("$", "");
total += price * quantity;
document.querySelector(".total-amount").innerText = "$" + total;
arr.push(quantity);
}
counter.innerText = arr.reduce(
(accumulator, currentValue) => accumulator + currentValue
);
}
我该怎么做?
答案 0 :(得分:6)
首先使用df.set_index
将y_axis
和x_axis
设置为索引。然后使用df.agg
,使用df.unstack
df1.set_index(['y_axis', 'x_axis']).agg(", ".join, axis=1).unstack(fill_value='')
x_axis p1 p2 p4
y_axis
1 error 2, error 3 error 2, error 3
2 error 1, error 4
3 error 1
5 error 1, error 4
答案 1 :(得分:2)
使用DataFrame.melt
删除可能的缺失值并通过DataFrame.pivot_table
进行整形,然后通过DataFrame.reindex
添加缺失的列和索引值,最后通过DataFrame.rename_axis
去除索引和列名称:
df1 = df1.replace('', np.nan)
cols = [f'p{x}' for x in range(1,6)]
idx = range(1,6)
df1 = (df1.melt(['x_axis','y_axis'])
.dropna()
.pivot_table(index='y_axis',
columns='x_axis',
values='value',
aggfunc=','.join,
fill_value='')
.reindex(columns=cols,index=idx, fill_value='')
.rename_axis(index=None, columns=None))
print (df1)
p1 p2 p3 p4 p5
1 error 2,error 3 error 2,error 3
2 error 1,error 4
3 error 1
4
5 error 1,error 4