Python 在具有整数命名列的数据帧中选择列
在以下数据框中,我可以使用列表访问两列:Python 在具有整数命名列的数据帧中选择列,python,pandas,Python,Pandas,在以下数据框中,我可以使用列表访问两列: df = pd.DataFrame(np.random.randn(4,4), index=[0,.5,1.,1.5], columns=['10', '20', '30', '40']) df[['10','20']] 10 20 0.0 1.048499 0.339459 0.5 -0.802472 1.348099 1.0 0.552306 -2.117145 1.5 1.737839 1.062061
df = pd.DataFrame(np.random.randn(4,4), index=[0,.5,1.,1.5], columns=['10', '20', '30', '40'])
df[['10','20']]
10 20
0.0 1.048499 0.339459
0.5 -0.802472 1.348099
1.0 0.552306 -2.117145
1.5 1.737839 1.062061
当列名为数字(本例中为整数)时,相同的切片将返回错误
df = pd.DataFrame(np.random.randn(4,4), index=[0,.5,1.,1.5], columns=[10, 20, 30, 40])
df[[10,20]]
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
当列名是数字而不是字符串时,如何获得相同的结果
有什么建议吗???你确定整数没有转换成字符吗 尝试: 或:
df[[1,2]]No,这将返回
KeyError:“['10''20']不在索引中”
df = pd.DataFrame(np.random.randn(4,4), index=[0,.5,1.,1.5], columns=[10, 20, 30, 40])
df[["10","20"]]