use*_*834 5 python numpy vectorization pandas
有这样的数据
import pandas as pd
tcd = pd.DataFrame({
'a': {'p_1': 1, 'p_2': 1, 'p_3': 0, 'p_4': 0},
'b': {'p_1': 0, 'p_2': 1, 'p_3': 1, 'p_4': 1},
'c': {'p_1': 0, 'p_2': 0, 'p_3': 1, 'p_4': 0}})
tcd
# a b c
# p_1 1 0 0
# p_2 1 1 0
# p_3 0 1 1
# p_4 0 1 0
Run Code Online (Sandbox Code Playgroud)
(但有40e3列)
我寻找一种矢量化方式来放置布尔值并在结果系列中:
a & b = ab -> 1 or True a & c = ac -> 0 or False
1 0 0 1 0 0
1 1 0 1 0 0
0 1 1 0 1 0
0 1 0 0 0 0
Run Code Online (Sandbox Code Playgroud)
现在我只得到一个带有for循环的丑陋解决方案::
res = pd.Series(index=['a&a', 'a&b', 'a&c'])
for i in range(3):
res[i] = (tcd.iloc[:, 0] & tcd.iloc[:, i]).any()
res
aa 1
ab 1
ac 0
Run Code Online (Sandbox Code Playgroud)
通过BM回答,我得到了这个
def get_shared_p(tcd, i):
res = (tcd.iloc[:, i][:, None] & tcd).any()
res.index += '&_{}'.format(i)
return res
res = pd.DataFrame(columns=range(cols), index=range(cols))
for col_i in range(cols):
res.iloc[:, col_i] = list(get_shared_p(tcd, col_i))
print res
# 0 1 2
# 0 True True False
# 1 True True True
# 2 False True True
Run Code Online (Sandbox Code Playgroud)
我们可以避免这个新的for循环.
用于[:,None]对齐数据并强制广播:
In[1] : res=(tcd.a[:,None] & tcd).any(); res.index+='&a'; res
Out[1]:
a&a True
b&a True
c&a False
dtype: bool
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
179 次 |
| 最近记录: |