用户为dataframe obj输入一个属性

2024-04-29 11:00:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图允许用户输入dataframe对象的属性

我试着把输入改成字符串。我也尝试过使用保存到变量中的输入。这两个选项都不起作用

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\u str'属性” 或者 “AttributeError:'DataFrame'对象没有'input1\u col'属性”


Tags: csv对象testdfinputdata属性col
1条回答
网友
1楼 · 发布于 2024-04-29 11:00:40

欢迎光临! 要访问pandas中的列,不能使用data.column 试试data[column]或者在你的情况下test[input1_col] 在此之前,请确保列确实存在,并且用户没有输入不存在的列

有时列名可以是整数,转换为字符串也可能是一个问题

您可以通过运行data.columns(如果您想要一个正则数组:list(data.columns))获得所有数据帧列的列表,实际上您可以通过运行data.columns = ["Column Header 1" , "Column Header 2" etc.]更改列名

相关问题 更多 >