Read lists into columns of pandas DataFrame

后端 未结 2 1449
囚心锁ツ
囚心锁ツ 2020-12-30 06:54

I want to load lists into columns of a pandas DataFrame but cannot seem to do this simply. This is an example of what I want using transpose() but I would thin

相关标签:
2条回答
  • 2020-12-30 07:30

    Someone just recommended creating a dictionary from the data then loading that into the DataFrame like this:

    In [8]: data = pd.DataFrame({'x': x, 'sin(x)': y})
    In [9]: data
    Out[9]: 
              x        sin(x)
    0  0.000000  0.000000e+00
    1  0.349066  3.420201e-01
    2  0.698132  6.427876e-01
    3  1.047198  8.660254e-01
    4  1.396263  9.848078e-01
    5  1.745329  9.848078e-01
    6  2.094395  8.660254e-01
    7  2.443461  6.427876e-01
    8  2.792527  3.420201e-01
    9  3.141593  1.224647e-16
    
    [10 rows x 2 columns]
    

    Note than a dictionary is an unordered set of key-value pairs. If you care about the column orders, you should pass a list of the ordered key values to be used (you can also use this list to only include some of the dict entries):

    data = pd.DataFrame({'x': x, 'sin(x)': y}, columns=['x', 'sin(x)'])
    
    0 讨论(0)
  • 2020-12-30 07:45

    Here's another 1-line solution preserving the specified order, without typing x and sin(x) twice:

    data = pd.concat([pd.Series(x,name='x'),pd.Series(y,name='sin(x)')], axis=1)
    
    0 讨论(0)
提交回复
热议问题