[英]Dynamically Appending new string to existing one
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
. 它应基于为a
列传递的值来选择b
列a
值。 Say I want to select all the values of column b
for value 2
in column a
and produce the following string 说我要选择列的所有值b
的值2
列a
并产生以下字符串
There are 3 values for value 2.
1. u
2. w
3. v
I am doing it using for
loop as below: 我正在使用for
循环,如下所示:
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. 上面的解决方案正在工作,但我正在寻找更多的efficeint解决方案。
Context: I'm creating a chatbot response. 上下文:我正在创建一个聊天机器人响应。 So trying to reduce the response time 因此,尝试减少响应时间
Any suggestions are welcome. 欢迎任何建议。
You can use to_string 您可以使用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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.