我有一個資料框:
df =
time id ser1 ser2 ... ser20 N0ch0 N1ch0 N2ch0 N0ch1 N1ch1 N2ch1 N0ch2 N1ch2 N2ch2 N0ch3 N1ch3 N2ch3
1 2 4 5 3 8 7 8 5 1 4 6 2 7 9 8 6
我想根據通道('ch'子字串)旋轉它,這樣它就會變成一列,所以新的資料框將是:
time id channel ser1 ser2 ... ser20 N0 N1 N2
1 2 0 4 5 3 8 7 8
1 2 1 4 5 3 5 1 4
1 2 2 4 5 3 6 2 7
1 2 3 4 5 3 9 8 6
最好的方法是什么?
uj5u.com熱心網友回復:
您可以首先使用melt將引數id_vars設定為“ser”,如列和“time” “id”。
然后,您可以將“變數”列拆分為 2,其中一列將在使用時用作索引列pivot_table,另一列將是column:
# Columns to be used as index in melt & pivot
id_cols = ['time','id'] list(df.filter(like='ser'))
# Melt and split a column
m = df.melt(id_vars = id_cols)
m[['N','channel']] = m.variable.str.split('ch', 1 ,expand=True)
# Pivot the melted dataframe
out = m.pivot_table(index = id_cols ['channel'], columns='N', values='value').reset_index()
印刷:
time id channel ser1 ser2 ser20 N0 N1 N2
0 1 2 0 4 5 3 8 7 8
1 1 2 1 4 5 3 5 1 4
2 1 2 2 4 5 3 6 2 7
3 1 2 3 4 5 3 9 8 6
uj5u.com熱心網友回復:
我們可以set_index用來保存任何不應該修改的列。然后str.split“ch”上的其余列似乎是新列名和通道號之間的分隔符。然后為了從 MultiIndex 列到長格式stack。reset_index跟進astype將新通道列從 aa 字串轉換為 int(如果需要)。
# columns to save
idx_cols = ['time', 'id', 'ser1', 'ser2']
res = df.set_index(idx_cols)
# Separate N value from channel number
res.columns = res.columns.str.split('ch', expand=True).rename([None, 'channel'])
# Go to long form
res = res.stack().reset_index()
# Convert to number from string
res['channel'] = res['channel'].astype(int)
res:
time id ser1 ser2 channel N0 N1 N2
0 1 2 4 5 0 8 7 8
1 1 2 4 5 1 5 1 4
或者wide_to_long可以使用它抽象一些重塑,但需要跟進str.extract以獲取通道號,并手動指定所有“存根名稱”:
# columns to save
idx_cols = ['time', 'id', 'ser1', 'ser2']
res = (
pd.wide_to_long(
df,
i=idx_cols,
j='channel',
stubnames=['N0', 'N1', 'N2'], # all stub names (add more if needed)
suffix=r'ch\d ' # suffix
).reset_index()
)
# Get only the channel numbers and convert to int
res['channel'] = res['channel'].str.extract(r'(\d $)').astype(int)
res
time id ser1 ser2 channel N0 N1 N2
0 1 2 4 5 0 8 7 8
1 1 2 4 5 1 5 1 4
任何一個選項的注釋idx_cols都可以動態創建而不是手動創建。
通過切片第一n列(此示例代碼為 4):
idx_cols = df.columns[:4]
或者通過根據條件過濾 DataFrame 列(如str.startswith:
idx_cols = ['time', 'id', *df.columns[df.columns.str.startswith('ser')]]
示例設定:
import pandas as pd
df = pd.DataFrame({
'time': [1], 'id': [2], 'ser1': [4], 'ser2': [5],
'N0ch0': [8], 'N1ch0': [7], 'N2ch0': [8],
'N0ch1': [5], 'N1ch1': [1], 'N2ch1': [4]
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/414797.html
標籤:
上一篇:根據一列將缺失值填充到另一列
