首先,我们应该了解数据框的理想字典应该是什么样子。
可以通过两种不同的方式来考虑 Dataframe:
一种是传统的行集合..
'row 0': ['jack', 100, 50, 'A'],
'row 1': ['mick', 107, 62, 'B']
不过,还有另一种更有用的表示,虽然一开始可能不那么直观。
列集合:
'name': ['jack', 'mick'],
'height': ['100', '107'],
'weight': ['50', '62'],
'grade': ['A', 'B']
现在,这是要实现的关键,第二个表示更有用
因为这是数据帧中相互支持和使用的表示。
它不会在单个分组中遇到数据类型冲突(每列需要有 1 个固定数据类型)
但是,在行表示中,数据类型可能会有所不同。
此外,可以在整个色谱柱上轻松一致地执行操作
因为这种连贯性是无法保证的。
因此,tl;dr DataFrame 本质上是等长列的集合。
因此,该表示形式的字典可以轻松转换为 DataFrame。
column_names = ["name", "height" , "weight", "grade"] # Actual list has 10 entries
row_names = ["jack", "mick"]
data = [100, 50,'A', 107, 62,'B'] # The actual list has 1640 entries
因此,考虑到这一点,首先要意识到的是,在其当前格式中,data 是一种非常糟糕的表示形式。
它是合并到单个列表中的行的集合。
如果您是控制数据形成方式的人,那么要做的第一件事就是不要以这种方式准备数据。
目标是每列的列表,理想情况下,以该格式准备列表。
但是,现在,如果以这种格式给出,您需要相应地迭代和收集值。这是一种方法
column_names = ["name", "height" , "weight", "grade"] # Actual list has 10 entries
row_names = ["jack", "mick"]
data = [100, 50,'A', 107, 62,'B'] # The actual list has 1640 entries
dic = {key:[] for key in column_names}
dic['name'] = row_names
print(dic)
目前的输出:
{'height': [],
'weight': [],
'grade': [],
'name': ['jack', 'mick']} #so, now, names are a column representation with all correct values.
remaining_cols = column_names[1:]
#Explanations for the following part given at the end
data_it = iter(data)
for row in zip(*([data_it] * len(remaining_cols))):
for i, val in enumerate(row):
dic[remaining_cols[i]].append(val)
print(dic)
输出:
{'name': ['jack', 'mick'],
'height': [100, 107],
'weight': [50, 62],
'grade': ['A', 'B']}
我们已经完成了表示
最后:
import pd
df = pd.DataFrame(dic, columns = column_names)
print(df)
name height weight grade
0 jack 100 50 A
1 mick 107 62 B
编辑:
zip部分的一些解释:
zip 接受任何可迭代对象,并允许我们一起迭代它们。
data_it = iter(data) #prepares an iterator.
[data_it] * len(remaining_cols) #creates references to the same iterator
这里,这类似于[data_it, data_it, data_it]
*[data_it, data_it, data_it] 中的 * 允许我们将列表解压缩为 zip 函数的 3 个参数
因此,对于任何函数 f,f(*[data_it, data_it, data_it]) 等价于 f(data_it, data_it, data_it)。
这里的神奇之处在于,遍历迭代器/推进迭代器现在将反映所有引用的变化
把它们放在一起:
zip(*([data_it] * len(remaining_cols))) 实际上允许我们一次从数据中获取 3 项,并将其分配给行
所以,row = (100, 50, 'A') 在 zip 的第一次迭代中
for i, val in enumerate(row): #just iterate through the row, keeping index too using enumerate
dic[remaining_cols[i]].append(val) #use indexes to access the correct list in the dictionary
希望对您有所帮助。