我有以下数据集: 名为:2,3,4...9 的列填充了相互重叠的主题名称。网页浏览量是一个结果变量。
2 3 Pageviews
0 Financial Services Consumer Products 4106.0
1 Consumer Products ... 3368.0
2 Consumer Products ... 1025.0
3 Collaboration ... 7840.0
4 Future of Supply Chains ... 2076.0
我想将每个主题列 (2,3, 4, ...) 与 Pageviews 一起切片并附加它们,以便只创建一个包含 1 个主题列和 的数据框浏览量。
我习惯于在 Stata 中循环,您可以在其中使用 x 循环遍历列的名称,但我知道这与 Pyhton 完全不同。
我从
开始for x in range(2, 9):
df_x = df[['Pageviews', df.x]]
但是 Python 不识别 df.x
如何遍历列名?是否可以使用迭代器创建新的数据帧?
谢谢!
编辑
我想要的输出是
Col Pageviews
0 Financial Services 4106.0
1 Consumer Products 3368.0
2 Consumer Products 1025.0
3 Collaboration 7840.0
4 Future of Supply Chains 2076.0
5 Future of Reporting 2123.0
6 Sustainability Management 15576.0
7 Human Rights 52.0
8 BSR News 903.0
9 Energy and Extractives 1232.0
10 HERproject 616.0
11 Sustainability Management 10697.0
其中 col 是附加第 2、3、4 列的结果……而 Pageviews 是附加相应的“Pageviews”列的结果。
请您参考如下方法:
使用融化
df.melt('Pageviews').drop('variable',1)
Out[644]:
Pageviews value
0 1210 ConsumerProducts
1 1528 Collaboration
2 1716 FinancialServices
3 1403 Collaboration
4 1090 ConsumerProducts
5 1210 ConsumerProducts
6 1528 FutureofSupplyChains
7 1716 ConsumerProducts
8 1403 FinancialServices
9 1090 FutureofSupplyChains
10 1210 FinancialServices
11 1528 FinancialServices
12 1716 Collaboration
13 1403 FutureofSupplyChains
14 1090 FinancialServices
