我有一个包含每个样本的不同区域的嵌套列表。我想创建一个数据帧,使每行(样本)都存在或不存在相应的区域(列)。例如,数据可能如下所示:
region_list = [['North America'], ['North America', 'South America'], ['Asia'], ['North America', 'Asia', 'Australia']]
结束数据框看起来像这样:
North America South America Asia Australia
1 0 0 0
1 1 0 0
0 0 1 0
1 0 1 1
我想我可能想出一种使用嵌套循环并附加的方法,但是有更多的pythonic方法吗?也许是numpy.where
?
答案 0 :(得分:6)
<强> 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
<强> 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
计时
%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
答案 1 :(得分:4)
让我们试试:
df = pd.DataFrame(region_list)
df2 = df.stack().reset_index(name='region')
df_out = pd.get_dummies(df2.set_index('level_0')['region']).groupby(level=0).sum().rename_axis(None)
print(df_out)
输出:
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
答案 2 :(得分:1)
这将完成这项工作!
unsigned int index(struct myDataStructure, void *value, bool *ok);
答案 3 :(得分:1)
您可以使用www
模块中的chain.from_iterable
和itertools
:
list comprehension
输出:
from itertools import chain
region_list = [['North America'], ['North America', 'South America'], ['Asia'], ['North America', 'Asia', 'Australia']]
regions = list(set(chain.from_iterable(region_list)))
vals = [[1 if j in k else 0 for j in regions] for k in region_list]
df = pd.DataFrame(vals, columns=regions)
print(df)