我嘗試使用 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 的屬性,因此不起作用。
uj5u.com熱心網友回復:
試試pandas.DataFrame.query(),你可以傳遞一個運算式。因此,您可以要求用戶插入運算式,然后將其傳遞給函式。
expr = input()
df.query(expr, inplace = True)
Pandas 查詢檔案
uj5u.com熱心網友回復:
DataFrame.loc 屬性:通過標簽或布爾 陣列訪問一組行和列。
DataFrame.iloc property : 純粹基于整數位置的索引,用于按位置選擇。
實際上,這些接受一個值作為文本字串以將其索引到相應的列,我建議您使用用戶輸入但對這些值進行條件處理
user_input_test.append(col_one)
one_condition_input = df.loc[df[user_input_test],:]
反而:
user_input_test.append(col_one)
cond = re.findall(r'\w ', user_input)
col = cond[0]
col_element = " ".join(cond[1:])
one_condition_input = df.loc[df[col == col_element],:]
.
.
.
>>> user_input = "State == New York" # User input value
>>> cond = re.findall(r'\w ', user_input) # Separate strings
['State', 'New', 'York']
>>> # This is equivalent to df.loc[df["State" == "New York"]]
>>> one_condition_input = df.loc[df[col == col_element],:] # Values correspoding to columns containing "New York" state.
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/370909.html
上一篇:既然字串標量是一個字符序列或陣列,為什么我們還需要字符向量作為字串標量組合單個字符?
下一篇:洗掉資料框中“\”之后的字符
