我有一些带有columnA
,columnB
,columnC
,columnD
... columnX
等列的DataFrame。
对于这些列中的所有行,我想用列名本身作为行值的前缀。
对于columnA
,例如:
第A列4
columnA 10
columnA 14
对于columnE
,例如:
columnE苹果
columnE香蕉
columnE橙色
对许多(〜30)列执行此操作的最佳方法是什么?
答案 0 :(得分:1)
假设您具有以下DataFrame。使用 WITH A AS(
Select 1 id , 'TRS1000i-082' as Machine , 5 pass, 2 fail union all
Select 2 id , 'TRS1000i-001' as Machine , 0 pass, 0 fail union all
Select 3 id , 'TRS1000i-001' as Machine , 20 pass, 0 fail
)
SELECT ID
,MACHINE
,pass
,null fail
FROM a
UNION ALL
SELECT ID
,MACHINE
,null pass
,fail fail
FROM a
order by ID
很简单:
apply
答案 1 :(得分:1)
您可以尝试广播:
df.columns.values[None,:] + ' ' + df.astype(str)
snowneji的数据帧输出:
a b c
0 a 1.0 b 1.0 c 1.0
1 a 1.0 b 1.0 c 1.0
2 a 1.0 b 1.0 c 1.0
3 a 1.0 b 1.0 c 1.0
4 a 1.0 b 1.0 c 1.0
答案 2 :(得分:0)
这有效:
column_subset = ['columnA', 'columnB', 'columnC', 'columnD',
'columnE']
for header in column_subset:
df[header] = header + df[header]