【发布时间】:2020-06-19 03:49:54
【问题描述】:
people1 trait1 YES
people1 trait2 YES
people1 trait3 NO
people1 trait4 RED
people2 trait1 NO
people2 trait2 YES
people2 trait4 BLACK
等等。
可以从该表中创建类似这样的内容吗?
trait1, trait2, trait3, trait4 ...
people1 YES YES NO RED
people2 NO YES - BLACK
people3 - - YES BLUE
文件太大,无法在 excel 中执行此操作,我在 pandas 中尝试过,但在这种情况下我找不到帮助。 我找到了 pd.pivot_table 函数,但我无法构建工作代码。我尝试并得到了各种错误(99% 是我的错)。
有人可以解释一下如何在我的情况下使用它吗?或者也许是比 pandas.pivot 更好的选择?+
编辑
I rebuild my frame:
1 'interpretation' 'trait'
p1 YES t1
p1 BLACK t2
p1 NO t3
p2 NO t1
p2 RED t2
p2 NO t3
我使用建议:
data1.pivot_table(index=1, columns="name", values='trait', aggfunc=','.join, fill_value='-')。
我得到了:
TypeError: sequence item 0: expected str instance, float found
如果我改变了
data1.pivot_table(index=1, columns="trait", values='value', aggfunc=','.join, fill_value='-')。
我得到了错误的订单表,但没有错误:
p1 p2 p3 p4
YES trait1 t1
YES t1 t2 etc.
NO
RED
No
...
所以我认为,第一个选项是正确的,但我无法修复该错误。当我 dtype df 它为所有列返回(O)。
【问题讨论】:
-
你能添加你的代码,错误吗?
-
通常:ValueError:索引包含重复的条目,即使我从df中删除重复项也无法重塑。我想我只是在逻辑上做错了事。我看到了你标记的那个帖子,但我可以根据它解决我的问题。
-
现在我的代码看起来是:
data1.pivot(index=1, columns=2, values=3).drop_duplicates()我的意思是枢轴部分,但我仍在继续尝试,这是最简单的版本。我试着用它做任何事情。 -
我建议使用
df = df.pivot_table(index='col1', columns='col2', values='col3', aggfunc=','.join, fill_value='-') -
感谢您的回答。它正在创建表。这与我需要的完全不同,但据我所知,我将列与参数不匹配。我会试试的。