将具有列名和值的列表转换为数据框并保留值

时间:2018-10-19 09:52:57

标签: python pandas list

我有列表形式的数据,看起来像['abc','bcd','cde',1,2,3]。我的问题是'abc','bcd'和'cde'是列名,而1,2,3是每列的值。

如何将列表转换为保留列名和相应值的数据框?

这是我的数据在列表中的样子:

[ sepal_length  sepal_width  petal_length  petal_width  species
0            5.1          3.5           1.4          0.2        0
1            4.9          3.0           1.4          0.2        0
2            4.7          3.2           1.3          0.2        0
3            4.6          3.1           1.5          0.2        0
4            5.0          3.6           1.4          0.2        0
5            5.4          3.9           1.7          0.4        0]

所以我不知道它内部是否仍然保留数据结构。

先谢谢您!

2 个答案:

答案 0 :(得分:2)

尝试一下:

l = ['abc','bcd','cde',1,2,3]
keys = l[:len(l)//2]
values = [[e] for e in l[len(l)//2:]]
pd.DataFrame(dict(zip(keys,values)))

返回

    abc     bcd     cde
0    1       2       3

如果每列的值大于1:

l = ['abc','bcd','cde',1,2,3,4,5,6]
n_columns = 3
#or
n_columns = len([e for e in l if isinstance(e,str)])
keys = l[:n_columns]
values = [list() for _ in range(n_columns)]
for i,e in enumerate(l[n_columns:]):
    values[i%n_columns].append(e)
pd.DataFrame(dict(zip(keys,values)))

返回

    abc     bcd     cde
0    1       2       3
1    4       5       6

答案 1 :(得分:1)

import pandas as pd
import numpy as np

nb_columns = 3
my_list = ['abc','bcd','cde',1,2,3]

# Extract the data from your list and reshape with the proper form (1 row, X columns)
data = np.reshape(my_list[nb_columns:], (1,nb_columns))

# Create a pandas Dataframe with your data and a list of columns name
my_pandas = pd.DataFrame(data, columns=my_list[:nb_columns])

编辑:多行

my_list = ['abc','bcd','cde',1,2,3,4,5,6]

# Try to count the number of rows present in the list
nb_row = int((len(my_list)-nb_columns)/nb_columns)

# Extract the data from your list and reshape with the proper form (N row, X columns)
data = np.reshape(my_list[nb_columns:], (nb_row, nb_columns))

如果还有其他问题。

相关问题