【问题标题】:DataFrame manipulation which dataframe do not have numeric value to aggretateDataFrame 操作哪个数据帧没有要聚合的数值
【发布时间】:2014-06-23 06:56:04
【问题描述】:

基本上,我有如下数据框

我想改变我上面的表格,结果如下 其中 [?] 需要从 [ColumnD] 列中查找值

我已经尝试过 Pandas.GroupBy 和 Pandas.Pivot,但它们没有给我带来任何运气。 Pandas.Pivot 需要数值字段中的数值,而 pandas.groupby 是一种混乱的过程

任何人都可以建议干净快速的方法来获得第二张表中的结果

欣赏:)

【问题讨论】:

  • 如果您在问题中包含可运行的代码和数据会有所帮助。阅读stackoverflow.com/help/mcve
  • 可复制粘贴的文本表格比图像更受欢迎。
  • 从上图中,将表格的左侧视为数据框,而右侧是我需要的结果...当我发出 pandas.pivot_table(df, rows=['Column_A','Column_b'], cols='column_c', values='Column_D').. 它弹出我没有聚合的数字
  • 任何方法都可以在 python 中使用,以便我的结果显示为图中表格的右侧......我还需要在列和行中查找值,如何执行它..它将是和 excel 中的 index..match 一样

标签: python numpy pandas


【解决方案1】:

你要找的方法是unstack

import pandas as pd
from StringIO import StringIO

data = \
"""Column_A;Column_B;Column_C;Column_D
12L; ITEM_a;  DEF;     12 (L1,L3)
12L; ITEM_B; DEF;      13 (L1,L3)
12L; ITEM_a; DEF;      14 (L1,L3)
12L; ITEM_N; DEF;      15 (L1,L3)
12L; ITEM_I; DEF;      16 (L1,L3)
12L; ITEM_P; SIDE_X;   17 (L1,L3)
8L;  ITEM_P; SIDE_x;   13 (L1,L3)
7L;  ITEM_A; SIDE_x;   19 (L1,L3)
1L;  ITEM_Q; SIDE_Y;   20 (L1,L3)
4L;  ITEM_I; SIDE_X;   21 (L1,L3)
4L;  ITEM_A; SIDEJ;    22 (L1,L3)
4L;  ITEMB;  SIDEJ;    23 (L1,L3)
4L;  ITEM_B; SIDE_X;   24 (L1,L3)
2L;  ITEM_A; SIDE_x;   25 (L1,L3)
3L;  Z;      SD_U;     26 (L1,L3)
8L;  XC;     AS;       27 (L1,L3)"""

# Creation of the dataframe
df = pd.read_csv(StringIO(data),sep = ';', index_col = [0,1,2])
# Perform the magic operation (unstack) on the dataframe
df = df.unstack(level=-1)
# Remove the first multilevel index in the columns
df.columns = df.columns.droplevel(0)
# Remove spaces contained in columns
df.columns = [i.strip() for i in df.columns.values]
print df

【讨论】:

  • [df.columns.droplevel(0)] 正在做合并过程??
  • 嗨,这次又提出了一个挑战,请参考下面的链接以获取我的文档 [sample][1] 仅供参考,该文档是 xls 文件,里面有 2 张,名为 raw_data 和 result_page 提供raw_data 在文件中,你们是否发现任何使用 python 的方法,pandas 具有与 result_page 表中类似的输出
  • 您需要使用命令 grouby 对列进行分组,还需要使用命令堆栈和取消堆栈。
猜你喜欢
  • 2018-05-14
  • 1970-01-01
  • 2016-04-29
  • 2018-03-04
  • 2021-05-06
  • 2022-11-18
  • 2019-08-09
相关资源
最近更新 更多