我有一個資料集 df,我想將來自不同列的某些值合并到一個“單元格”中:
資料
hello hi ok bye
q122 q222 q422 q222
hi hi hi hi
邏輯
The first two rows are joined

想要的
hello_q122 hi_q222 ok_q422 bye_q222
hi hi hi hi
正在做
df.columns = (df.iloc[0] '_' df.iloc[1])
df = out.iloc[0:].reset_index(drop=True)
但是,第一行不斷被洗掉。
任何建議表示贊賞。
uj5u.com熱心網友回復:
您需要[1]通過空字串設定第二行 ( ) 并通過[1:]以下方式過濾第一行:
#solution if default header
print (df)
0 1 2 3
0 hello hi ok bye
1 q122 q222 q422 q222
2 hi hi hi hi
df.columns = df.iloc[0] '_' df.iloc[1]
df.iloc[1] = ''
df = df.iloc[1:].reset_index(drop=True)
print (df)
hello_q122 hi_q222 ok_q422 bye_q222
0
1 hi hi hi hi
df.to_csv(file, index=False)
#solution if first row is header
print (df)
hello hi ok bye
0 q122 q222 q422 q222
1 hi hi hi hi
df.columns = (df.columns '_' df.iloc[0])
df.iloc[0] = ''
df = df.reset_index(drop=True)
print (df)
hello_q122 hi_q222 ok_q422 bye_q222
0
1 hi hi hi hi
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/341056.html
