熊猫Python用户输入了数据框对象的属性

时间:2019-07-24 19:38:37

标签: python pandas

我正试图允许用户输入数据框对象的属性。

我尝试将输入更改为字符串。我也尝试使用输入保存到变量中。这两个选项都不起作用。

data = pd.read_csv('2019FallEnrollees.csv')

input1_col = input("Enter comparison group A: ")
input2_col = input("Enter comparison group B: ")

input1_str= str(input1_col)
input2_str = str(input2_col)

test = data[['CUM_GPA', input1_str, input2_str]]

# error here! 'test' does not have attribute 'input1_str' or 'input1_col'
df_1 = test[(test.input1_str == 0) & (test.input2_str == 0)]
df_2 = test[(test.input1_col == 1) & (test.input2_col == 0)]

print(stats.ttest_ind(df_1.CUM_GPA, df_2.CUM_GPA, equal_var = False))

错误消息说

“ AttributeError:“ DataFrame”对象没有属性“ input1_str” 要么 “ AttributeError:“ DataFrame”对象没有属性“ input1_col”

1 个答案:

答案 0 :(得分:0)

欢迎光临! 要访问熊猫列,您不能使用data.column 尝试data[column]或您的情况test[input1_col] 在执行此操作之前,请确保该列确实存在,并且用户没有输入不存在的列。

有时列名可以是整数,也可能需要转换为字符串

您可以通过运行data.columns(如果要使用常规数组:list(data.columns))来获取所有数据框列的列表,实际上,您可以通过运行data.columns = ["Column Header 1" , "Column Header 2" etc.]来更改列名。 / p>