給定資料框:
d = {'col1': [1, 2, 3, 4, 7], 'col2': [4, 5, 6, 9, 5], 'col3': [7, 8, 12, 1, 11], 'col4': [12, 13, 14, 15, 16]}
將第三列附加到第一列并將第四列附加到第二列的最簡單方法是什么?
結果應該是這樣的。
d = {'col1': [1, 2, 3, 4, 7, 7, 8, 12, 1, 11], 'col2': [4, 5, 6, 9, 5, 12, 13, 14, 15, 16],
我需要將其用于具有不同列名的腳本,因此無法按名稱參考列。我已經嘗試了一些類似 df.iloc[:,x] 的方法來實作這一點。
uj5u.com熱心網友回復:
您可以更改列名和concat:
pd.concat([df[['col1', 'col2']],
df[['col3', 'col4']].set_axis(['col1', 'col2'], axis=1)])
添加ignore_index=True程序中重置索引。
輸出:
col1 col2
0 1 4
1 2 5
2 3 6
3 4 9
4 7 5
0 7 12
1 8 13
2 12 14
3 1 15
4 11 16
或者,使用numpy:
N = 2
pd.DataFrame(
df
.values.reshape((-1,df.shape[1]//2,N))
.reshape(-1,N,order='F'),
columns=df.columns[:N]
)
uj5u.com熱心網友回復:
您可以使用:
out = pd.concat([subdf.set_axis(['col1', 'col2'], axis=1)
for _, subdf in df.groupby(pd.RangeIndex(df.shape[1]) // 2, axis=1)])
print(out)
# Output
col1 col2
0 1 4
1 2 5
2 3 6
3 4 9
4 7 5
0 7 12
1 8 13
2 12 14
3 1 15
4 11 16
uj5u.com熱心網友回復:
這可能不是最有效的解決方案,但您可以使用 pandas 中的pd.concat()函式來完成。
首先將您的初始 dictd轉換為 apandas Dataframe然后應用 concat 函式。
d = {'col1': [1, 2, 3, 4, 7], 'col2': [4, 5, 6, 9, 5], 'col3': [7, 8, 12, 1, 11], 'col4': [12, 13, 14, 15, 16]}
df = pd.DataFrame(d)
d_2 = {'col1':pd.concat([df.iloc[:,0],df.iloc[:,2]]),'col2':pd.concat([df.iloc[:,1],df.iloc[:,3]])}
d_2是你需要的字典。如果需要,將其轉換為資料框,
df_2 = pd.DataFrame(d_2)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/459196.html
上一篇:我正在嘗試將csv轉換為xlsx檔案我收到錯誤“沒有要從檔案決議的列”
下一篇:如何在變數結果后命名資料框索引?
