代码如下,目的是从df中一行行取出,将'B’列相等的行存放到a,并将这些行从df中删除
操作以后a中多出两列分别是level_0和index,df中多出level_0一列
import pandas as pd
df = pd.DataFrame([['a', 1, 'a1'], ['a', 1, 'a2'], ['b', 2, 'b1'], ['b', 2, 'b2'], ['c', 3, 'c1']])
df.columns = ['A', 'B', 'C']
x = df.iloc[0]['B']
a = pd.DataFrame(columns=['A', 'B', 'C'])
while True:
if x == df.iloc[0]['B']: # 判断是否与第一行时间相等
a = a.append(df.iloc[0, :]) # 加入存储队列
df.drop(0, inplace=True)
df.reset_index(inplace=True)
else:
break
a.reset_index(inplace=True)
print(a)
print(df)
显示结果:
level_0 A B C index
0 0 a 1 a1 NaN
1 0 a 1 a2 1.0
level_0 index A B C
0 1 2 b 2 b1
1 2 3 b 2 b2
2 3 4 c 3 c1
Process finished with exit code 0