I have a csv file that i imported to pandas df. Lets say it is something like this
# A B C D
# 0 foo one 0 0
# 1 bar one 1 2
# 2 foo two 2 4
# 3 bar three 3 6
# 4 foo two 4 8
# 5 bar two 5 10
# 6 foo one 6 12
# 7 foo three 7 14
When i use "foo" to search there is no problem and the statement below works as expected.
print(df.loc[df['A'] == 'foo'])
BUT when i use a "variable x" i.e. instead of "foo" to search in the Column A it doesn't return anything.
print(df.loc[df['A'] == variablex])
print(df.loc[df['A'] == 'variablex'])
How can i solve this problem. Thanks a lot for your help.
CodePudding user response:
You mean like this?:
df = pd.DataFrame([
("foo","one",0,0),
("bar","one",1,2),
("foo","two",2,4),
("bar","three",3,6),
("foo","two",4,8),
("bar","two",5,10),
("foo","one",6,12),
("foo","three",7,14),
], columns = ["A","B","C","D"])
variablex = "foo"
print(df.loc[df["A"] == variablex])
Output:
A B C D
0 foo one 0 0
2 foo two 2 4
4 foo two 4 8
6 foo one 6 12
7 foo three 7 14
I'm not sure I see what the problem is, so not sure if we've answered your question.