【问题标题】:pandas: first steps with merge, join, and concatenatepandas:合并、连接和连接的第一步
【发布时间】:2016-11-02 04:50:57
【问题描述】:

我有一个像下面这样的数据框,有 3 列和 12 行。 12 行是 4 个重复的类(3 次)。我知道我从来没有 1A、1D、2B 和 2D 单元格的值,并且我总是有 1B、1C、2A 和 2C 单元格的单元格值。

我想将其转换为您在下面看到的内容,其中我将列名和行名组合起来以提取所有我知道其中将始终包含数据的单元格。 这样,我将避免不必要的重复或不必要的空单元格。

我已尝试阅读手册http://pandas.pydata.org/pandas-docs/stable/merging.html,但我有一些难以采取正确的方法。给我一些建议?

非常感谢

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    你可以使用:

    #get index to MultiIndex in column
    df = df.set_index(['class','date']).unstack(level=0)
    #remove columns with all NaN, sort index
    df = df.dropna(axis=1, how='all').sort_index(ascending=False)
    #reset MultiIndex in columns, cast int to str in first level (1,2 values)
    df.columns = [''.join((str(col[0]),col[1])) for col in df.columns]
    #index to column
    df.reset_index(inplace=True)
    #reorder columns
    df = df[df.columns[1:].union(df.columns[:1])]
    print (df)
             1B        1C        2A            2C        date
    0  1.462543  4.920529  4.496126  3.362060e+08  2016-10-31
    1  3.931170  3.439862  2.453640  1.488948e+00  2016-10-30
    2  3.550311  3.504713  3.224958  1.804881e+00  2016-10-29
    

    【讨论】:

    • 首先非常感谢您,您很客气。我有这个错误: ``` TypeError Traceback (last recent call last) in () 8 # print col 9 ---> 10 df.columns = [''.join (col) for col in df.columns] 11 ''' 12 #index to column TypeError: sequence item 1: expected string, int found ``
    • 您需要将int 转换为str - 使用df.columns = [''.join((str(col[0]),col[1])) for col in df.columns]
    • 再次感谢您,但它似乎不起作用。我有 3 行 x 25 列,而不是 3 行 x 5 列。我已经在这个要点中插入了所有内容gist.github.com/aborruso/8eb51579335cd94d44c033bea2b27748
    • 您需要df = df.set_index(['class','date']).unstack(level=0) - 为两列设置索引。在我认为class 列是索引之前。
    • 有效!!! gist.github.com/aborruso/8eb51579335cd94d44c033bea2b27748非常感谢,我真的很惊讶
    猜你喜欢
    • 2018-05-23
    • 2019-12-13
    • 2014-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-24
    • 2015-11-25
    相关资源
    最近更新 更多