这里的初学者:请善良。我想显示pandas DataFrame操作的结果,但我无法去掉结果周围的括号。这是一个小程序,可以从数据帧中随机选择一个条目。
import pandas as pd
import random as rd
## enter choices
choicelist=[]
while True:
entry =input('Enter an option (q to quit}')
if entry =='q':
break
else:
choicelist.append(entry)
## create df with weights
df= pd.DataFrame(choicelist, columns= ['Choice'])
df['Weight']= 1/len(df)
df['CumWeight']=df['Weight'].cumsum()
## generate random number
a= rd.random()
selection = df['Choice'][(a<=df.CumWeight) & (a>df.CumWeight-df.Weight)].values
print ('Random selected choice: '+selection)
## there is still a bracket around the result...
例如,当输入"a"、"b"时
['Random selected choice: a']
但我想要:"随机选择:a"PS:数据帧没有括号:
df
Out[92]:
Choice Weight CumWeight
0 a 0.5 0.5
1 b 0.5 1.0
设置选择时,即使数组中只有一个项,.values
也会返回一个numpy数组。当您将字符串'Random selected choice: '
添加到numpy数组时,它仍然是一个numpy数组,因此将使用括号打印。要解决这个问题,您可以只从选择中提取第一个项目:print ('Random selected choice: '+selection[0])
,并且它应该打印为一个正常的字符串,不带括号。