Python Pandas 數據框將 col 的值重塑為新的 col

手槍

我有一個看起來像這樣的數據框:

    col1    col2    col3    col4    col5    col6    
0   1.1     a       29      b       c       d
1   2.3     a       29      b       c       d
2   10.3    a       29      b       c       d
3   6.5     a       29      b       c       d
4   34.7    a       29      b       c       d

5   6.3     e       25      f       g       h
6   7.1     e       25      f       g       h
7   36.0    e       25      f       g       h
8   74.2    e       25      f       g       h
9   64.7    e       25      f       g       h

我想重塑它,使其看起來像:

    col1    col2    col3    col4    col5    col6    col7    col8    col9    col10
0   a       29      b       c       d       1.1     2.3     10.3    6.5     34.7
1   e       25      f       g       h       6.3     7.1     36.0    74.2    64.7

我試過了

df = df.groupby('col2')['col1'].apply(list)

col2 
a    [1.1, 2.3, 10.3, 6.5, 34.7]
b    [6.3, 7.1, 36.0, 74.2, 64.7]

但是我不知道如何從列表中獲取每個值到一個新的列。

耶斯列

使用GroupBy.cumcountDataFrame.pivot

df['new'] = df.groupby(['col2','col3','col4','col5','col6']).cumcount()

df = df.pivot(index=['col2','col3','col4','col5','col6'], columns='new', values='col1').reset_index()
df.columns = [f'col{i + 1}' for i in range(len(df.columns))]
print (df)
  col1  col2 col3 col4 col5  col6  col7  col8  col9  col10
0    a    29    b    c    d   1.1   2.3  10.3   6.5   34.7
1    e    25    f    g    h   6.3   7.1  36.0  74.2   64.7

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

使用 col 名稱創建的 Pandas 數據框

Python / Pandas:选择具有多个条件的数据框行-col 1匹配col 2或col 3

Python - Pandas - 將列名複製到新數據框而不帶數據

使用 python 和 Pandas 將多數組 json 數據轉換為扁平數據框

如果它们的值在 col2 但不在 Python Pandas 的列表中,如何从 col1 中选择值?

根据其他列的值计算 pandas 中的列(如果 col1<col2 和 col2 > col1,则 col3 = 1)

使用 pandas col 以 dict 格式存储 % 的值

替换 df col-pandas 中的值

选择配对行,Col Pandas 值

在python中如何將字符串列表轉換為pandas數據框

將列表類型字典轉換為 Pandas 數據框 - python

將python列表轉換為pandas數據框的問題

根據其他 col 值計算 col 的唯一出現次數

Pandas - 如果在 (col B) 中观察到列 (col A) 中的值,则使用来自 (col C) 的值创建列 (col D)

Pandas - 根據 COL2 中的唯一值更改 COL1 中的多個值,其中 COL1 中的值已滿足條件

將 Json 轉換為 Pandas 數據框

將 txt 文件轉換為 Pandas 數據框

Pandas 數據框將行轉換為列

Pandas:將數據框轉換為嵌套字典

如何使用 Pandas 數據框將 R 代碼語法轉換為 Python 語法?

將 XML 數據解析為 Pandas python

在 Python 中將系列轉換為數據框

用列表替换col中的唯一值-Pandas

如何使用 Pandas 將舊數據框中的最大值複製到新數據框中?

Pandas Dataframe - 按 Col A 分组并对每组 Col C 求和

將python中的無序數據更改為有序數據框

如果 DF col 中存在单词,如何在 Pandas 数据框中搜索 col 并列出列表

使用条件语句将值映射到单独的col:python

Pandas 為 pyspark 數據框應用函數替代(想要將整數數據類型列轉換為列表數據類型)