Flo*_*wen 4 python numpy pandas
我有一个包含每个样本的不同区域的嵌套列表.我想创建一个数据帧,使每行(样本)都存在或不存在相应的区域(列).例如,数据可能如下所示:
region_list = [['North America'], ['North America', 'South America'], ['Asia'], ['North America', 'Asia', 'Australia']]
Run Code Online (Sandbox Code Playgroud)
结束数据框看起来像这样:
North America South America Asia Australia
1 0 0 0
1 1 0 0
0 0 1 0
1 0 1 1
Run Code Online (Sandbox Code Playgroud)
我想我可能想出一种使用嵌套循环和附加的方法,但是有更多的pythonic方法来做到这一点吗?或许有numpy.where?
pandas
str.get_dummies
pd.Series(region_list).str.join('|').str.get_dummies()
Asia Australia North America South America
0 0 0 1 0
1 0 0 1 1
2 1 0 0 0
3 1 1 1 0
Run Code Online (Sandbox Code Playgroud)
numpy
np.bincount 同 pd.factorize
n = len(region_list)
i = np.arange(n).repeat([len(x) for x in region_list])
f, u = pd.factorize(np.concatenate(region_list))
m = u.size
pd.DataFrame(
np.bincount(i * m + f, minlength=n * m).reshape(n, m),
columns=u
)
North America South America Asia Australia
0 1 0 0 0
1 1 1 0 0
2 0 0 1 0
3 1 0 1 1
Run Code Online (Sandbox Code Playgroud)
定时
%timeit pd.Series(region_list).str.join('|').str.get_dummies()
1000 loops, best of 3: 1.42 ms per loop
%%timeit
n = len(region_list)
i = np.arange(n).repeat([len(x) for x in region_list])
f, u = pd.factorize(np.concatenate(region_list))
m = u.size
pd.DataFrame(
np.bincount(i * m + f, minlength=n * m).reshape(n, m),
columns=u
)
1000 loops, best of 3: 204 µs per loop
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
153 次 |
| 最近记录: |