python - 在执行操作时转置此表的最快方法
问题描述
我有这个:
name phenotype
ID1 tall
ID2 tall
ID3 short
ID4 tall
我要这个:
ID1 ID2 ID3 ID4 phenotype
yes yes no yes tall
no no yes no short
我试过这种方法:
df = pd.DataFrame({'name' : ['ID1', 'ID2', 'ID3', 'ID4'], 'phenotype' : ['tall', 'tall', 'short', 'tall']})
sample_dict = {}
for sample in df['name']:
var_list = []
for variant in df['phenotype'].unique():
sample_subset = df[df['name'] == sample]
if variant in sample_subset['phenotype'].to_list():
var_list.append('yes')
else:
var_list.append('no')
sample_dict[sample] = var_list
sample_dict['phenotype'] = ['tall', 'short']
sample_df = pd.DataFrame(sample_dict)
在执行我描述的操作时,是否有更好更快的转置该表的方法?
解决方案
尝试pd.crosstab
:
print(
pd.crosstab(df["phenotype"], df["name"])
.replace({0: "no", 1: "yes"})
.reset_index()
.rename_axis("", axis=1)
)
印刷:
phenotype ID1 ID2 ID3 ID4
0 short no no yes no
1 tall yes yes no yes
推荐阅读
- ionic-framework - 如何在 ionic3 中更新时向 tabBadge 未读消息计数添加声音
- r - 使用 expss 包在 R 中的顶部 2 个 boxES 和底部 2 个盒子网
- reactjs - 将道具传递给新的 URL/路由
- html - href="../" 链接到根目录而不是父目录
- python - 如何使直方图条居中?
- angular - 如何从角度应用程序读取和写入本地文件
- gradle - Maven-Publish 未生成适当的任务
- amazon-web-services - 在 api 网关上启用 cors
- python - TfidfVectorizer toarray() 和 HashingVectorizer 的含义
- php - Mysql、PHPmyadmin 和 Apache 的 Docker 错误