Python 如何比较两列的值并基于比较对值重新排序
我是python新手,我遇到了一个难题,我不知道如何去做。我需要比较两列中的值,然后根据此比较对值重新排序。例如,假设我们有以下数据帧。现在我需要检查B中的值,如果它们小于A的累积和中的值。如果B中的值高于A的cum,那么我们停在那一行。我们根据B列的数值对观测结果重新排序,直到该行(也包括该行)为止 例如,当我们看B中的值时,我们看到所有的值都小于A中的值,直到第4部分 零件号 A. B 一杯 1. 2. 13 2. 2. 4. 17 6. 3. 7. 15 13 4. 5. 16 18 5. 10 19 28 6. 9 16 37 7. 8. 12 45 这应该起作用:Python 如何比较两列的值并基于比较对值重新排序,python,dataframe,Python,Dataframe,我是python新手,我遇到了一个难题,我不知道如何去做。我需要比较两列中的值,然后根据此比较对值重新排序。例如,假设我们有以下数据帧。现在我需要检查B中的值,如果它们小于A的累积和中的值。如果B中的值高于A的cum,那么我们停在那一行。我们根据B列的数值对观测结果重新排序,直到该行(也包括该行)为止 例如,当我们看B中的值时,我们看到所有的值都小于A中的值,直到第4部分 零件号 A. B 一杯 1. 2. 13 2. 2. 4. 17 6. 3. 7. 15 13 4. 5. 16 18 5.
import pandas as pd
data = [ { "Part No": 1, "A": 2, "B": 13, "cum of A": 2 }, { "Part No": 2, "A": 4, "B": 17, "cum of A": 6 }, { "Part No": 3, "A": 7, "B": 15, "cum of A": 13 }, { "Part No": 4, "A": 5, "B": 16, "cum of A": 18 }, { "Part No": 5, "A": 10, "B": 19, "cum of A": 28 }, { "Part No": 6, "A": 9, "B": 16, "cum of A": 37 }, { "Part No": 7, "A": 8, "B": 12, "cum of A": 45 } ]
df = pd.DataFrame(data)
smaller_indexes = len(df[df['B'] > df['cum of A']]) + 1 # check where B is larger than 'cum of A', take the length of that part of the dataframe and add 1 to get the index number of the last value to use for sorting
df[:smaller_indexes] = df[:smaller_indexes].sort_values(by=['B']) # slice the dataframe by the found index number, and sort only that slice of the dataframe
df['cum of A'] = df['A'].cumsum() #recount the cumsum of the entire dataframe
这将输出:
零件号
A.
B
一杯
0
1.
2.
13
2.
1.
3.
7.
15
9
2.
4.
5.
16
14
3.
2.
4.
17
18
4.
5.
10
19
28
5.
6.
9
16
37
6.
7.
8.
12
45
我知道这有点粗糙,但如果您愿意,您可以使用以下选项:
#order the values in list
def order(a):
for i in range(len(a)):
# print(i)
b = a[i-1] - a[i]
if b>0:
temp = a[i-1]
a[i-1] = a[i]
a[i] = temp
for j in range(i,0,-1):
b = a[j-1] - a[j]
if b>0:
temp = a[j-1]
a[j-1] = a[j]
a[j] = temp
return a
b = [13,15,16,17,19,16,12]
a = [2, 7, 5, 4, 10, 9, 8]
#other list to append the last value if cum is greater than value of "b" after ordering b
otherList = []
# isRecursive and indexToTake is for:
# "And if there is still a higher value in cum of A than the values in B
# among these reordered observations (first four parts), then part 4 will be
# taken out from the list and put in a separate list."
def solve(isRecursive, indexToTake):
c = 0
for i in range(len(a)):
c += a[i] #cum sum
if c> b[i]: #check if cum is greater than the value of "b" at that index
if isRecursive:
if i >indexToTake:
return
otherList.append(b[indexToTake])
return
b[0:i+1] = order(b[0:i+1])
solve(True, i) #check if the values at "b" are greater than cum after ordered until the indexToTake
break
solve(False, 0) #start solving