【发布时间】:2022-01-07 08:50:38
【问题描述】:
我试图使用 loc 在条件下获取数据框中的行子集,但我想获取用户输入以获取此条件,然后将其输入 loc 语句以创建行子集。
我尝试了很多方法,但我认为 loc 不会接受这种格式的字符串中的条件,有没有办法解决这个问题?
请参阅下面的尝试:
col_one = input("Please enter the condition you would like to set. E.g. State == "New York":)
user_input_test.append(col_one)
one_condition_input = self.df.loc[self.df[user_input_test],:]
# I also tried to use slice but no luck:
col_one = input("Please enter the condition you would like to set. E.g. State == "New York":)
period = slice(col_one)
self.one_condition_input = self.df.loc[period,:]
# And I tired to use format, taking two user inputs, one with column name and one with the condition, but again no luck:
col_one = input("Please enter the column you would like to set. E.g. State":)
col_two = input("Please enter the condition you would like to set. E.g. == "New York":)
one_condition_input = self.df.loc[self.df["{}".format(col_one)]"{}".format(col_two),:]
我希望能够获取整个条件的用户输入并将其粘贴如下:
col_one = input("Please enter the condition you would like to set. E.g. State == "New York":)
self.one_condition_input = self.df.loc[df.col_one,:]
但显然这里 col_one 不是 df 的属性,因此不起作用。
【问题讨论】:
标签: python pandas string user-input pandas-loc