Kel*_*ref 2 regex string dataframe pandas
我有一个数据帧如下:
<A> "B" C _:D <E>
A B "C" <D> E>
<A> "B" "C" D <E>
Run Code Online (Sandbox Code Playgroud)
我试图找到一种方法来检查哪些元素以"<"或""或"_:"开头,并返回如下数据帧:
1 1 0 1 1
0 0 1 1 0
1 1 1 0 1
Run Code Online (Sandbox Code Playgroud)
由于数据帧的大小,不使用apply.理想情况下,我的最终数据框如下:
<A> "B" C _:D <E> 4
A B "C" <D> E> 2
<A> "B" "C" D <E> 4
Run Code Online (Sandbox Code Playgroud)
谢谢
更新:
如何在原始数据帧中添加一个包含堆栈+ unstack中找到的1的总和的列?
In [59]: df['new'] = df.stack().str.contains(r'^(?:\"|<|_:)').astype(np.uint8).sum(level=0)
In [60]: df
Out[60]:
0 1 2 3 4 new
0 <A> "B" C _:D <E> 4
1 A B "C" <D> E> 2
2 A< B" C" D E< 0 # pay attention at this row
Run Code Online (Sandbox Code Playgroud)
老答案:
试试这个:
df.apply(lambda col: col.str.contains(r'^\"|<|_:').astype(np.uint8))
Run Code Online (Sandbox Code Playgroud)
演示:
In [33]: df.apply(lambda col: col.str.contains(r'^\"|<|_:').astype(np.uint8))
Out[33]:
0 1 2 3 4
0 1 1 0 1 1
1 0 0 1 1 0
2 1 1 1 0 1
Run Code Online (Sandbox Code Playgroud)
或者使用stack()+ unstack():
In [36]: df.stack().str.contains(r'^\"|<|_:').astype(np.uint8).unstack()
Out[36]:
0 1 2 3 4
0 1 1 0 1 1
1 0 0 1 1 0
2 1 1 1 0 1
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
407 次 |
| 最近记录: |