実現したいこと
以下のカラム構成で
| N0 | N1 | N2 | N4 | tx1 | tx2 | tx3 | tx4 |
|---|---|---|---|---|---|---|---|
| A | C | B | D | A | B | C | D |
の表がありますこれを
Resカラムを追加して
以下の様に出力するコードを作成したいのです
| N0 | N1 | N2 | N4 | tx1 | tx2 | tx3 | tx4 | Res |
|---|---|---|---|---|---|---|---|---|
| A | C | B | D | A | B | C | D | N0 N2 N1 N4 |
Resカラムを新設して
tx1-tx4までの順に沿って
N0、N1、N2、N4のカラム名を順番に並べ格納する
なお、N0、N1、N2、N4のカラムとtx1-tx4は
順番はそれぞれ異なるが同じ要素になっている
上記のコードを作成したいが作成がうまくいきません
途中まで書いてコードです
環境:Google colab
python
1import pandas as pd 2 3 4data = {5 'N0': ['A'],6 'N1': ['C'],7 'N2': ['B'],8 'N4': ['D'],9 'tx1': ['A'],10 'tx2': ['B'],11 'tx3': ['C'],12 'tx4': ['D']13}14 15df = pd.DataFrame(data)16print(df)17 18 19n_columns_order = df.columns[0:df.columns.get_loc('tx1')]20 21# Resカラムを作成し、各行の値を計算する関数を定義22def calculate_res(row):23 tx_columns = row[['tx1', 'tx2', 'tx3', 'tx4']].tolist()24 selected_columns = n_columns_order 25 return ' '.join(col for col in n_columns_order if row[col][0] in tx_columns)26 27# applyを使用してResカラムを計算28df['Res'] = df.apply(calculate_res, axis=1)29 30# 結果の表示31print(df[['Res']])32 33 34 35 36############37これでうまくいかない意味が分からない 38 39 N0 N1 N2 N4 tx1 tx2 tx3 tx4 400 A C B D A B C D 41 Res 420 N0 N1 N2 N4 43

0 コメント