簡體   English   中英

pandas 中的多行變成單行

[英]multiple rows into single row in pandas

我希望展平(我不確定將其稱為展平是否正確)帶有行的列。 多行變為單行,列更改為 column_rows 我有一個 dataframe 如下:

data = {"a":[3,4,5,6],
      "b":[88,77,66,55],
      "c":["ts", "new", "thing", "here"],
      "d":[9.1,9.2,9.0,8.4]}
df = pd.DataFrame(data)

我目前的 output 是:

    a   b   c   d
0   3   88  ts  9.1
1   4   77  new 9.2
2   5   66  thing   9.0
3   6   55  here    8.4

我的預期輸出:

    a_0  a_1 a_2 a_3 b_0 b_1 b_2 b_3 c_0 c_1 c_2 c_3 d_0 d_1 d_2 d_3
0   3 4 5 6 88 77 66 55 ts new thing here 9.1 9.2 9.0 8.4

從形狀 (4,4) 到 (1, 16)

試試這個,使用unstackto_frame和轉置。 接下來,使用列表推導展平列標題:

df_new = df.unstack().to_frame().T 
df_new.columns = [f'{i}_{j}' for i, j in df_new.columns]
df_new

Output:

  a_0 a_1 a_2 a_3 b_0 b_1 b_2 b_3 c_0  c_1    c_2   c_3  d_0  d_1  d_2  d_3
0   3   4   5   6  88  77  66  55  ts  new  thing  here  9.1  9.2  9.0  8.4

一種選擇是使用pyjanitorpivot_wider

# pip install pyjanitor
import pandas as pd
import janitor

(df
.assign(
    header = df.index, 
    index = 0)
.pivot_wider(
    index = 'index', 
    names_from = 'header',
    names_sep = '_')
.drop(columns='index')
)
   a_0  a_1  a_2  a_3  b_0  b_1  b_2  b_3 c_0  c_1    c_2   c_3  d_0  d_1  d_2  d_3
0    3    4    5    6   88   77   66   55  ts  new  thing  here  9.1  9.2  9.0  8.4

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM