【问题标题】:Using a function to create a string from numbers使用函数从数字创建字符串
【发布时间】:2022-01-24 00:49:01
【问题描述】:

我正在尝试在 python 中创建一个函数,该函数将给定列的前 10 个 ID 作为字符串返回,该字符串将成为新列的值。例如,如果前 10 个 id 为 [1,2,3,4,5,6,7,8,9,10],则输出应为“1 2 3 4 5 6 7 8 9 10”。当我应用我拥有的函数时,它只返回空白值。

对于上下文,这是我的数据集 HF_2018 的样子:

这是我目前的功能:

def top_ten(month):
top_funds = ""
top_ten = np.array(HF_2018[HF_2018['month']==month-1].nlargest(10, 'Performance')['Fund_ID'])
for i in top_ten:
    top_funds += str(i)
return top_funds

这是我尝试创建新列的方式:

HF_2018['top_10'] = top_ten(HF_2018['month'])

任何帮助都会很棒。谢谢!

【问题讨论】:

    标签: python pandas function numpy


    【解决方案1】:

    从数字数组形成字符串的一种方法是使用astype 将它们转换为单独的字符串:

    In [206]: x = np.arange(5)
    In [207]: x.astype('U5')
    Out[207]: array(['0', '1', '2', '3', '4'], dtype='<U5')
    

    然后使用join 将它们与您想要的任何分隔符连接起来:

    In [208]: ' '.join(x.astype('U5'))
    Out[208]: '0 1 2 3 4'
    

    【讨论】:

      猜你喜欢
      • 2023-04-09
      • 1970-01-01
      • 2011-08-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-10
      • 1970-01-01
      相关资源
      最近更新 更多