Python - Pandas,将长列拆分为多列

标签 python pandas

给定以下 DataFrame:

>>> pd.DataFrame(data=[['a',1],['a',2],['b',3],['b',4],['c',5],['c',6],['d',7],['d',8],['d',9],['e',10]],columns=['key','value'])
  key  value
0   a      1
1   a      2
2   b      3
3   b      4
4   c      5
5   c      6
6   d      7
7   d      8
8   d      9
9   e     10

我正在寻找一种可以根据键值更改结构的方法,如下所示:

   a  b  c  d   e
0  1  3  5  7  10
1  2  4  6  8  10 <- 10 is duplicated
2  2  4  6  9  10 <- 10 is duplicated

结果行号是最长的组计数(上例中的 d),缺失值是最后一个可用值的重复值。

最佳答案

通过 set_index 创建 MultiIndex带计数器列 cumcount , 通过 unstack reshape , 用 ffill 用最后一个非缺失值替换缺失值,并在必要时最后将所有数据转换为 integer:

df = df.set_index([df.groupby('key').cumcount(),'key'])['value'].unstack().ffill().astype(int)

另一种具有自定义 lambda 函数的解决方案:

df = (df.groupby('key')['value']
        .apply(lambda x: pd.Series(x.values))
        .unstack(0)
        .ffill()
        .astype(int))

print (df)
key  a  b  c  d   e
0    1  3  5  7  10
1    2  4  6  8  10
2    2  4  6  9  10

关于Python - Pandas,将长列拆分为多列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53522060/

相关文章:

python - 与报价处理完全混淆

python - 如何通过加入 Pandas 中的现有列来创建新列

python - django 对象中的 save 方法不保存 bool 模型字段,它传递的是 false

python - 如何创建一个函数来传递 BeautifulSoup

python - Google App Engine - 为特定网址编写 app.yaml,如 applicationName.appspot.com/docs/ec-quickstart/index.html

python - 在python中删除字符串格式的负号

python - 根据条件分成不同的行

python pandas.loc 找不到行名称 : KeyError

python - 根据 Pandas 中的多个条件过滤行

python-3.x - 排序数据透视表(多索引)