I have a dataframe.
df = pd.DataFrame({'a':[1,1,2,2,2], 'b':['x','y','u','w','v']})
It should select the values of column b
based on value passed for column a
. Say I want to select all the values of column b
for value 2
in column a
and produce the following string
There are 3 values for value 2.
1. u
2. w
3. v
I am doing it using for
loop as below:
x = df[df['a']==2]['b'].values
result = "There are {} values for 2.\n".format(len(x))
z = ""
for i, val in enumerate(x):
temp = "{}. {}\n".format(i+1, val)
z += temp
print(result+z)
Above solution is working but I'm looking for more efficeint solution.
Context: I'm creating a chatbot response. So trying to reduce the response time
Any suggestions are welcome.
You can use to_string
x = df.loc[df.a == 2, 'b']
print('There are {} values for value 2.\n'.format(len(x)))
print(x.reset_index(drop = True).to_string())
There are 3 values for value 2.
0 u
1 w
2 v
Another sol:
m=df.loc[df['a'].eq(2),'b']
m.index=list(range(1,len(m)+1))
print('There are {} values for value 2.\n'.format(len(x)))
print(m.to_string())
There are 3 values for value 2.
1 u
2 w
3 v
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.