<p>你可以试试这个:</p>
<pre><code>(df.temp_col.groupby((~df.temp_col.str.contains(r",\\$")).shift().fillna(True).cumsum())
.apply(lambda x: "".join(x.str.rstrip(r",\\"))))
#temp_col
#1 matt
#2 joes\crabshack\one23
#3 fail
#4 joe:1231234567892313456123412391234321321143
#5 john
#6 jacob
#7 joe(x):54398765441231234
#Name: temp_col, dtype: object
</code></pre>
<p>分解:</p>
<p>1)创建一个组变量,当元素不以<code>,\</code>结尾时,将在其中生成一个新组:</p>
<pre><code>g = (~df.temp_col.str.contains(r",\\$")).shift().fillna(True).cumsum()
g
#0 1
#1 2
#2 3
#3 4
#4 4
#5 4
#6 4
#7 4
#8 5
#9 6
#10 7
#11 7
#12 7
#Name: temp_col, dtype: int64
</code></pre>
<p>2)定义一个<code>join</code>函数,去掉结尾的逗号和反斜杠</p>
<pre><code>join_clean = lambda x: "".join(x.str.rstrip(r",\\"))
</code></pre>
<p>3)对每个组应用join函数以连接以<code>,\</code>结尾的连续行:</p>
<pre><code>df.temp_col.groupby(g).apply(join_clean)
#temp_col
#1 matt
#2 joes\crabshack\one23
#3 fail
#4 joe:1231234567892313456123412391234321321143
#5 john
#6 jacob
#7 joe(x):54398765441231234
#Name: temp_col, dtype: object
</code></pre>