串联字符串的Pandas KeyError

时间:2019-11-16 21:56:53

标签: python pandas dataframe indexing concatenation

df_test = df[0].head(4)
count_array = ' \'Page_count_0\''
count_array = '[\'Index_0\', \'VAstart\','  + count_array + ']'
print('{}'.format(count_array))
df_test['{}'.format(count_array)]

KeyError:“ ['Index_0','VAstart','Page_count_0']”

出于完整性考虑,我试图从巨大的数据框中打印以下列

Index_0 VAstart Count_0 Count_1 Count_2 Count_3 Count_4 Count_5

1 个答案:

答案 0 :(得分:0)

您定义它的方式,count_array包含一个字符串:

"['Index_0', 'VAstart', 'Page_count_0']"

除非我有误解(因为您没有包含有关数据框的任何信息),否则您只是在尝试选择键列表来访问数据框。如果是这样,可以将count_array定义为

count_array = 'Page_count_0'
count_array = ['Index_0', 'VAstart', count_array]

这样count_array是一个键列表,而不仅仅是一个长字符串:

['Index_0', 'VAstart', 'Page_count_0']

您可以直接访问df_test[count_array]