python - Pandas:使用重复值进行透视

标签 python pandas dataframe pivot

我想旋转一个在一列中具有重复值的数据框,以在新列中显示关联值,如下例所示。从 Pandas 文档中我无法弄清楚如何从这里开始......

name   car    model
rob    mazda  626
rob    bmw    328
james  audi   a4
james  VW     golf
tom    audi   a6
tom    ford   focus

为此...

name   car_1  model_1  car_2  model_2
rob    mazda  626      bmw    328
james  audi   a4       VW     golf
tom    audi   a6       ford   focus

最佳答案

x = df.groupby('name')['car','model'] \
      .apply(lambda x: pd.DataFrame(x.values.tolist(),
             columns=['car','model'])) \
      .unstack()
x.columns = ['{0[0]}_{0[1]}'.format(tup) for tup in x.columns]

结果:

In [152]: x
Out[152]:
       car_0 car_1 model_0 model_1
name
james   audi    VW      a4    golf
rob    mazda   bmw     626     328
tom     audi  ford      a6   focus

如何对列进行排序:

In [157]: x.loc[:, x.columns.str[::-1].sort_values().str[::-1]]
Out[157]:
      model_0  car_0 model_1 car_1
name
james      a4   audi    golf    VW
rob       626  mazda     328   bmw
tom        a6   audi   focus  ford

关于python - Pandas:使用重复值进行透视,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43764983/

相关文章:

python - 生产服务器上的 IOError

python - 将 Pandas 列转换为用户定义的周数

python - 在数据框的列上应用 map 功能

python-3.x - 按日期时间索引的 pandas DataFrame 的一周内操作

python - python中用逗号分隔数字

Python等于运算符,避免: (<string> == <number>) -> False类型的bug

python - 在 ipython 解释器中执行文件

python - 在 Pandas 中将元组设置为列名

python - 使用 pandas 合并索引

Python pandas dataframe 转换不带小数的值