![](/img/trans.png)
[英]Python: Combine for loop in while loop and iterate rows in a data
[英]python while loop to combine and delete repeated rows
我得到了一個像這樣的數據框:
Type: Volume: Date: Price:....
Q 10 2016.6.1 10
Q 20 2016.6.1 20
T 10 2016.6.2
Q 10 2016.6.3
T 20 2016.6.4
T 20 2016.6.5
Q 10 2016.6.6
並且我只想在兩個(或多個)T連續的情況下將'volume'的值相加,並刪除該行之一
即:
Q 10 2016.6.1
Q 20 2016.6.1
T 10 2016.6.2
Q 10 2016.6.3
T 20+20=40 2016.6.4
Q 10 2016.6.6
現在我正在使用一個if循環:
l = len(df)
Volume = df['Volume']
Type = df['Type']
for i in range(2,l-1):
if Type[i] == 'Trade':
if Type[i] == 'Trade' and Type[i+1] == 'Trade' :
Volume[i] = Volume[i]+Volume[i+1]
df = np.delete(fd, (i), axis=0)
但是,我得到一個錯誤:
ValueError: Shape of passed values is (8, 303540), indices imply (8, 303541)
另外,我想將'if'循環更改為'while'循環,這樣,如果有兩個以上連續的'Trade'數據類型,我可以更輕松地處理數據
如果要在循環時編輯一個可迭代的對象,通常更安全的方法是在循環中處理數據的副本,然后用該更新的副本替換原始對象。 這樣可以避免Python對其在迭代中的位置感到困惑(這是您的錯誤中似乎暗示的問題,因為它抱怨索引)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.