Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
163 views
in Technique[技术] by (71.8m points)

python - Compositing a DataFrame column based on a new scale

I have a data frame that looks like this.

interval = np.arange(1,11)
length = 0.5*np.random.randint(low=4, high=7, size=10)
grade = np.random.randint(low=1, high=10, size=10)

data = {"interval": interval, "length": length, "grade": grade}
df = pd.DataFrame(data=data1)


 interval length  grade
0   1      3.0     2
1   2      2.0     6
2   3      2.5     4
3   4      2.5     1
4   5      3.0     8
5   6      2.0     8
6   7      2.0     4
7   8      2.0     6
8   9      2.0     9
9   10     3.0     5

So, what I want to do is create a new data frame with new "length" values that should be equal to 2. The corresponding grade values should be composited accordingly.

For example, since the first 'length' value in the old data frame is 3 and its grade is 2, the first-grade value in the new data frame should be 2. However, we still have '1' length with a grade of 2 unused. It should be added to the second row in a way that its grade should be (1x2+1x6)/2 since we have a length of 2 with a grade of 6 in the second row of the old data frame and so on. So they should be composited. The new data frame should have 12 rows, contrary to the old one, which has 10 since the total length is 24 and the new data frame will divide this length into parts of two.

The new data frame should be looking like this.


 interval length  grade
0   1      2.0     2
1   2      2.0   (1*2+1*6)/2
2   3      2.0   (1*6+1*4)/2
3   4      2.0   (1.5*4+0.5*1)/2
4   5      2.0     1
5   6      2.0     8
6   7      2.0   (1*8+1*8)/2
7   8      2.0   (1*8+1*4)/2
8   9      2.0   (1*4+1*6)/2
9   10     2.0   (1*6+1*9)/2
10  11     2.0   (1*9+1*5)/2
11  12     2.0     5

So, I hope I could have explained it properly. If you guys have any tips on that, I'd really appreciate it.

question from:https://stackoverflow.com/questions/66060935/compositing-a-dataframe-column-based-on-a-new-scale

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...