从乘法表打印输出生成DataFrame - Python 3.x.

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (171)

在我的下面的代码中,我正在生成随机生成的乘法表的打印输出。我想将每个表生成一个DataFrame。我该怎么办?(Python 3.x中的新功能)

这个练习是生成一个乘法表。它扩展为一个项目,用于生成一组乘法表,其中包含随机生成的一位或两位数的列和行号。目前它设置为运行五个表,每个表有8列和行。但是,这些数字可以改变。Jupyter Notebook最多只能打印12列。虽然我们的程序将生成任意数量的列和行(大小相等,例如,6x6,3x3,9x9等),但将其限制为12x12矩阵或更小,最适合查看。

import pandas as pd
import numpy as np
%matplotlib notebook

# This sets up how many tables we will generate
for t in range(0,5):

    # Make variable place holders for our columns and rows list
    a=[]
    b=[]

    # To use randomly generated numbers, this sets up the random column numbers 'a' and random row numbers 'b'
    import random
    for x in range(12):
        a.append(random.randint(41,99)) # We can adjust the range of the random selection of numbers here
        b.append(random.randint(1,35)) # We can adjust the range of the random selection of number here


    # Add the column titles for each table - these are the random numbers 'a'
    print("C/R: ", end="\t ")
    for number in a:
        print(number,end = '\t ')
    print()

    # The double for-loop to generate the table
    for row in b:
        print(row, end="\t") # First column
        for number in a:
            print(round(row*number,1),end='\t' )# Next columns
        print( )

    # Add two blank cosmetic lines between tables for readability
    print('\n\n')

谢谢。

提问于
用户回答回答于

稍微重构您的代码应该提供所需的输出。

import pandas as pd
import numpy as np
%matplotlib notebook

# This sets up how many tables we will generate

dataframes = []

for t in range(0,5):

    # Make variable place holders for our columns and rows list
    a=[]
    b=[]

    # To use randomly generated numbers, this sets up the random column numbers 'a' and random row numbers 'b'
    import random
    for x in range(12):
        a.append(random.randint(41,99)) # We can adjust the range of the random selection of numbers here
        b.append(random.randint(1,35)) # We can adjust the range of the random selection of number here

    data = []

    for row in b:
        temp = []
        for number in a:
            temp.append(round(row*number,1))

        data.append(temp)

    dataframe = pd.DataFrame(data=data, columns=a)
    dataframe.index = b

    dataframes.append(dataframe)

dataframes[0]

这是输出。

熊猫数据框

扫码关注云+社区

领取腾讯云代金券

年度创作总结 领取年终奖励