【问题标题】:how can I create new table based on the previous table in pandas?如何根据 pandas 中的前一个表创建新表?
【发布时间】:2019-04-02 19:06:05
【问题描述】:

关注这篇文章 How to reorder indexed rows based on a list in Pandas data frame

import pandas as pd
df = pd.DataFrame({'name' : ['A', 'Z','C'],
                   'company' : ['Apple', 'Yahoo','Amazon'],
                   'height' : [130, 150,173]})

df = df.pivot(index="name", columns="company", values="height").fillna(0)

df.reindex(["Z", "C", "A"])


company Amazon  Apple   Yahoo
name            
   Z     0.0    0.0     150.0
   C.  173.0    0.0      0.0
   A     0.0   130.0     0.0

我想知道我是否添加了更多数据并通过点击此链接Is there a way to copy only the structure (not the data) of a Pandas DataFrame?来做到这一点

df_1 = pd.DataFrame({'name' : ['A','Z','B','C','D'],
                   'company' : ['Apple','Yahoo','Alebaba','Amazon','Google'],
                   'height' : [130, 150,160,173,180]})

df_1 = df_1.pivot(index="name", columns="company", values="height").fillna(0)

df_1 = df_1.reindex_like(df)

结果如下所示

company Amazon  Apple   Yahoo
    name            
       Z     0.0    0.0     150.0
       C   173.0    0.0      0.0
       A     0.0   130.0     0.0

但我想看到这样的结果

company Amazon  Apple   Yahoo   Alebaba Google
name                    
 Z       0.0    0.0     150.0    0.0    0.0
 C     173.0    0.0       0.0    0.0    0.0
 A       0.0    130.0     0.0    0.0    0.0
 B       0.0    0.0       0.0   160.0   0.0
 D       0.0    0.0       0.0    0.0    180.0

这对小数据没问题,但如果是一千个数据,我该如何解决这个问题?

将添加到之前数据中的数据集可以位于任意位置。

有什么建议吗? T T

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    Index.differenceIndex.append 一起用于没有排序值的新索引和列值,并通过DataFrame.reindex 更改位置:

    print (df_1.index.difference(df.index))
    Index(['B', 'D'], dtype='object', name='name')
    
    print (df.index.append(df_1.index.difference(df.index)))
    Index(['Z', 'C', 'A', 'B', 'D'], dtype='object', name='name')
    

    idx = df.index.append(df_1.index.difference(df.index))
    cols = df.columns.append(df_1.columns.difference(df.columns))
    df_1 = df_1.reindex(index=idx, columns=cols)
    print (df_1)
    company  Amazon  Apple  Yahoo  Alebaba  Google
    name                                          
    Z           0.0    0.0  150.0      0.0     0.0
    C         173.0    0.0    0.0      0.0     0.0
    A           0.0  130.0    0.0      0.0     0.0
    B           0.0    0.0    0.0    160.0     0.0
    D           0.0    0.0    0.0      0.0   180.0
    

    【讨论】:

    • 感谢您的建议。我很好地遵循了它,但我想将上表中的行和列修复为我的预期结果
    • @HookIm - 哎呀,我错过了更改的列,请检查编辑后的答案。
    • 我在想,我几乎要搜索如何重新列 LOL。再次感谢您的建议!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-20
    • 2019-04-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多