【问题标题】:Restructure Python Dataframe重构 Python 数据框
【发布时间】:2018-11-24 15:37:43
【问题描述】:

我有一个 python 数据框,我需要对其进行重组以适应用例。

数据框如下:

index  | Probability
Value1 |  .98
Value2 |  .90
Value3 |  .85
Value4 |  .80

我需要重组数据框如下,第一行是标题:

Match1 | Probab1 | Match2 | Prob2 | Match3 | Prob3 | Match4 | Prob4 
Value1 | .98     | Value2 | .90   | Value2 | .85   | Value4 | .80

有没有使用 Pandas 和 Python 的简单方法?

【问题讨论】:

  • 我认为您正在尝试转置 DataFrame,或者基本上将列与行切换。试试df = df.T 看看是否有帮助。您可能还需要重命名某些列。
  • 不,转置将概率放在第二行,我需要它们与值相邻。
  • 一个更完整的例子会有所帮助。目前,您的 DataFrame 中没有“匹配”值,因此不清楚如何将它们放入您想要的输出中。

标签: python pandas dataframe iteration


【解决方案1】:

stack + transpose 将得到你想要的,只需稍作重命名。如果index 实际上是您的索引,则只需执行df = df.reset_index()

import pandas as pd
print(df)
#    index  Probability
#0  Value1         0.98
#1  Value2         0.90
#2  Value3         0.85
#3  Value4         0.80

df = df.stack().reset_index()

# Rename things
df.loc[df.level_1 == 'index', 'level_1'] = 'Match' + (df.loc[df.level_1 == 'index', 'level_0']+1).astype('str')
df.loc[df.level_1 == 'Probability', 'level_1'] = 'Prob' + (df.loc[df.level_1 == 'Probability', 'level_0']+1).astype('str')

df = df.drop(columns='level_0').T.reset_index(drop=True)

df 现在是:

        0      1       2      3       4      5       6      7
0  Match1  Prob1  Match2  Prob2  Match3  Prob3  Match4  Prob4
1  Value1   0.98  Value2    0.9  Value3   0.85  Value4    0.8

【讨论】:

  • 这非常有效!我必须做的唯一编辑是在 drop 命令中添加 'axis=1':df = df.drop(columns='level_0', axis=1).T
猜你喜欢
  • 1970-01-01
  • 2021-06-04
  • 1970-01-01
  • 1970-01-01
  • 2020-02-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多