Python Concat基于条件的列值
此代码:Python Concat基于条件的列值,python,pandas,Python,Pandas,此代码: import numpy as np import pandas as pd df = pd.DataFrame(['a1', 'a2', 'stop', 'a4', 'a4', 'a5', 'stop', 'a3'], columns=['c']) 呈现: c 0 a1 1 a2 2 stop 3 a4 4 a4 5 a5 6 stop 7 a3 我试图生成以下数据帧,其中列中的值被连接,直
import numpy as np
import pandas as pd
df = pd.DataFrame(['a1', 'a2', 'stop', 'a4', 'a4', 'a5', 'stop', 'a3'],
columns=['c'])
呈现:
c
0 a1
1 a2
2 stop
3 a4
4 a4
5 a5
6 stop
7 a3
我试图生成以下数据帧,其中列中的值被连接,直到遇到“stop”值:
columns = ['c1' , 'c2']
data = np.array([['a1, a2','stop'] , ['a4, a4, a5','stop']])
df = pd.DataFrame(data, columns=columns)
df
c1 c2
0 a1, a2 stop
1 a4, a4, a5 stop
如果这是一种有效的方法,请过滤列值为“stop”的行:
df[df['c'] == 'stop']
然后访问前面的行?首先,通过测试
c
与“stop”的相等性来创建布尔掩码:
您还指定要在最终停止后忽略值。使用以下命令截断两个序列:
>>> stop = mask[::-1].idxmax()
>>> mask = mask[:stop]
>>> c = df['c'][:stop].copy()
现在分组:
>>> c.groupby(mask.cumsum()).apply(lambda s: s[s!='stop'].tolist())
c
0 [a1, a2]
1 [a4, a4, a5]
对于累积和,True
映射为1,False
映射为0。这就是分组
脚注-无论序列中的最终值是否以
stop
结束,此逻辑都应起作用。最后一个a3
值会发生什么情况?@coldspeed a3值应忽略,不是应该是[['a1,a2','stop',['a4,a5','stop']
?不清楚第二行中的a3
的位置from@SeijiArmstrong您的问题已更新,谢谢。接受的答案仍然有效。@blue sky Prefilter first:df=df.loc[:df.c.eq('stop')[:-1].idxmax()]
您正在计算df.c.eq('stop')
,所以一定要重用掩码;)只是一个小小的改进,为什么不把过滤器移到外面应用,这会加快它的速度up@Wen我不确定这在这里是否可行?因为s[s!='stop]
分别应用于每个子系列。但如果我错了,请编辑
>>> c.groupby(mask.cumsum()).apply(lambda s: s[s!='stop'].tolist())
c
0 [a1, a2]
1 [a4, a4, a5]