簡體   English   中英

根據熊貓中各行的唯一值創建新列

[英]Creating new columns from unique values across rows in pandas

我正在嘗試在pandas列中使用唯一值來生成一組新列。 這是一個示例DataFrame

    meas1  meas2  side  newindex
0       1      3     L         0
1       2      4     R         0
2       6      8     L         1
3       7      9     R         1

我想將我的測量列與關鍵列“相乘”以生成如下所示的DafaFrame

   meas1_L  meas1_R  meas2_L  meas2_R
0        1        2        3        4
1        6        7        8        9

請注意,它本質上是這個問題的反面

使用DataFrame.pivot

# Perform the pivot.
df = df.pivot(index='newindex', columns='side').rename_axis(None)

# Format the columns.
df.columns = df.columns.map('_'.join)

結果輸出:

   meas1_L  meas1_R  meas2_L  meas2_R
0        1        2        3        4
1        6        7        8        9

使用groupby.prod另一種解決方案:

df = df.groupby(['side', 'newindex']).prod().unstack(level=0)
df.columns = ['_'.join(c[0::]) for c in df.columns]

          meas1_L  meas1_R  meas2_L  meas2_R
newindex                                    
0               1        2        3        4
1               6        7        8        9

暫無
暫無

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

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