【问题标题】:pivot data frame in pandas?大熊猫中的枢轴数据框?
【发布时间】: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='-')
  • 感谢您的回答。它正在创建表。这与我需要的完全不同,但据我所知,我将列与参数不匹配。我会试试的。

标签: python pandas dataframe


【解决方案1】:

我认为问题在于trait 列中缺少值,因此join 函数失败。所以可能的解决方案是将缺失值替换为空字符串:

print (data1)
    1   name trait
0  p1    YES   NaN <- missing value
1  p1  BLACK    t2
2  p1     NO    t3
3  p2     NO    t1
4  p2    RED    t2
5  p2     NO    t3

data1['trait'] = data1['trait'].fillna('')
df = data1.pivot_table(index=1, 
                       columns="name", 
                       values='trait', 
                       aggfunc=','.join, 
                       fill_value='-')
print (df)
1      p1     p2
name            
BLACK  t2      -
NO     t3  t1,t3
RED     -     t2
YES            -

如果要将索引转换为列:

data1['trait'] = data1['trait'].fillna('')
df = (data1.pivot_table(index=1, 
                       columns="name", 
                       values='trait', 
                       aggfunc=','.join, 
                       fill_value='-')
           .reset_index()
           .rename_axis(None, axis=1))
print (df)
    name  p1     p2
0  BLACK  t2      -
1     NO  t3  t1,t3
2    RED   -     t2
3    YES          -

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-08
    • 2019-01-07
    • 1970-01-01
    • 2022-06-12
    • 2020-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多