我有一个数据帧。
df = pd.DataFrame({'a':[1,1,2,2,2], 'b':['x','y','u','w','v']})
它应该根据为b
列传递的值选择列a
的值。假设我想在列b
中为值2
选择列a
的所有值并生成以下字符串
There are 3 values for value 2.
1. u
2. w
3. v
我正在使用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)
以上解决方案正在运行,但我正在寻找更有效的解决方案。
上下文:我正在创建一个聊天机器人响应。所以试图减少响应时间
欢迎任何建议。
你可以使用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
另一个溶胶:
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