Pandas 使用变量作为列名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36235304/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 00:56:31  来源:igfitidea点击:

Pandas use variable for column names

python-3.xpandas

提问by Dance Party

Given the following data frame:

给定以下数据框:

import pandas as pd
import numpy as np
df = pd.DataFrame({'A':[1,2,3],
                   'B':[4,5,6],
                   'C':[7,8,9]})

df

    A   B   C
0   1   4   7
1   2   5   8
2   3   6   9

How can I access columns via a variable?

如何通过变量访问列?

I tried this:

我试过这个:

cols='A','B'
df[cols]

...which resulted in this:

...导致了这个:

KeyError: ('A', 'B')

Bonus Question: What if my data frame were like this?:

额外问题:如果我的数据框是这样的怎么办?:

import pandas as pd
import numpy as np
df = pd.DataFrame({'A':[1,2,3],
                   'B':[4,5,6],
                   'C':[7,8,9],
                   'D':[1,3,5],
                   'E':[5,3,6],
                   'F':[7,4,3]})

df

    A   B   C   D   E   F
0   1   4   7   1   5   7
1   2   5   8   3   3   4
2   3   6   9   5   6   3

and I wanted to do this?:

我想这样做?:

cols=['A','B']
cols2=['C','D']
df[cols,'F',cols2]

Thanks in advance!

提前致谢!

采纳答案by jezrael

You can try subset by listof column names:

您可以尝试按list列名进行子集:

cols=['A','B']
print df[cols]
   A  B
0  1  4
1  2  5
2  3  6

It is same as:

它与:

print df[['A','B']]
   A  B
0  1  4
1  2  5
2  3  6

Bonus answer:

奖金答案:

cols=['A','B']
cols2=['C','D']

allcols = cols + ['F'] + cols2
print df[allcols]
   A  B  F  C  D
0  1  4  7  7  1
1  2  5  4  8  3
2  3  6  3  9  5