【问题标题】:Reshape panda dataframe in a specific way以特定方式重塑熊猫数据框
【发布时间】:2020-02-14 13:22:16
【问题描述】:

我是 Python 新手,我想重塑数据结构以进行进一步分析。我想重塑表格,以便每个 ID 只能有一行。我读到有些图书馆可以做到这一点,但我不知道怎么做。

所附示例的代码如下所示:

import pandas as pd

data = {'ID': [123, 123], 'Method': ['angular', 'angular'], 'Colour': ['red', 'blue'] }

df = pd.DataFrame (data, columns = ['ID','Method','Colour'])
df

每一个帮助都将不胜感激

提前致谢

Reshape_data

【问题讨论】:

  • 附加示例的代码如下所示: 附加示例的代码如下所示: import pandas as pd data = {'ID': [123, 123], 'Method': ['angular ', 'angular'], 'Color': ['red', 'blue'] } df = pd.DataFrame (data, columns = ['ID','Method','Colour']) df

标签: python file dataframe reshape transformation


【解决方案1】:

unstack 是你这种重塑的朋友。可能的代码是:

resul = df.reset_index().set_index(['ID', 'Method', 'index']
                                   ).unstack().reset_index()

# clean up the column names
resul.columns = [i if j == '' else i + '_' + str(j)
                 for i, j in resul.columns.tolist()]

它按预期给出:

    ID   Method Colour_0 Colour_1
0  123  angular      red     blue

【讨论】:

    猜你喜欢
    • 2017-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-03
    相关资源
    最近更新 更多