I have a dataframe:
value
id
742 aa
1711 bb
1731 qq
1799 ff
2741 pp
id is index column. I want to print only those values from column "value" which are in this list: [742, 1731, 1799]. So the output must be:
aa
qq
ff
How to do that?
I tried this:
for i in [742, 1731, 1799]:
print(df[df.index == i]["value"])
but the output is:
value
742 aa
Name: value, dtype: object
value
1731 qq
Name: value, dtype: object
value
1799 ff
Name: value, dtype: object
CodePudding user response:
This should do it:
Restating the problem:
ids = [
{"id":"742", "value":"aa"},
{"id":"1711", "value":"bb"},
{"id":"1731", "value":"qq"},
{"id":"1799", "value":"ff"},
{"id":"2741", "value":"pp"}]
df = pd.DataFrame(data=ids)
df = df.set_index(["id"])
This gets you the filtered list:
filtered_df = df[df.index.isin(["742","1731","1799"])]
CodePudding user response:
Use .set_index
to declare 'id'
as the index, then .loc[...]
to specify the list of indices you're interested in.
df = pd.DataFrame({'id': [8, 13, 21, 34, 55, 89], 'val': 'for sale baby shoes never worn'.split()}).set_index('id')
print(df)
# val
# id
# 8 for
# 13 sale
# 21 baby
# 34 shoes
# 55 never
# 89 worn
print(df.loc[[13,89]])
# val
# id
# 13 sale
# 89 worn
CodePudding user response:
for i in df:
if i.index in [742, 1731, 1799]:
# print(i.value)
# print(i["value"])