【问题标题】:How can I put the result of a derived function into a DataFrame?如何将派生函数的结果放入 DataFrame?
【发布时间】:2022-01-25 19:11:17
【问题描述】:

import pandas as pd

def fib(num):
   if num <= 2:
       return 1
   else:
       return(fib(num-1) + fib(num-2))




def lo():
 A1 = int(input("number of days you want? = "))


 if A1 <= 0:    
    print("NO!404")
 else:
     print("daily rabbit population")   
     for i in range(A1): 
         print(fib(i))
        
lo()        



data = {'Product': [lo()]}

        

df = pd.DataFrame(data, columns= ['Product', 'Price'])

print (df)

我让它工作,但它的结果。

你想要多少天? = 12 每日兔子数量 1 1 1 2 3 5 8 13 21 34 55 89 你想要多少天? = 12 每日兔子数量 1 1 1 2 3 5 8 13 21 34 55 89 产品价格 0 无 NaN

【问题讨论】:

  • 如何停止循环?
  • 预期输出是什么?
  • ลูปของฉันจะถูกให้สิ้นสุดจำนวนที่ในในa1 = int(输入(你想要的天数?=“))corralien span>
  • 预期的结果是我想把斐波那契数列的结果放到DataFrame中。
  • 如果符合您的预期,您能看看我的回答吗?

标签: python-3.x pandas


【解决方案1】:

修改你的lo函数如下:

def lo():
    A1 = int(input("number of days you want? = "))

    if A1 <= 0:    
        print("NO!404")
    else:
        print("daily rabbit population")   
        return [fib(i) for i in range(A1)]

data = {'Product': lo()}  # remove []
df = pd.DataFrame(data, columns= ['Product', 'Price'])

输出:

>>> df
    Product Price
0         1   NaN
1         1   NaN
2         1   NaN
3         2   NaN
4         3   NaN
5         5   NaN
6         8   NaN
7        13   NaN
8        21   NaN
9        34   NaN
10       55   NaN
11       89   NaN

【讨论】:

  • 哦,非常感谢(:
  • 很高兴读到。如果这适合您的需要,请考虑accept my answer :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-23
  • 2020-07-25
  • 2018-12-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多