Python 从 narray/lists 的 dict 创建 DataFrame
正如我们所知,Pandas是用于数据分析的所有时间的伟大工具。其中一个最重要的数据类型是数据框架。它是一个二维标签的数据结构,具有潜在的不同类型的列。它通常是最常用的pandas对象。
Pandas DataFrame可以通过多种方式创建。让我们来讨论如何使用ndarray(或lists)的字典来创建Pandas数据框架。
让我们试着用几个例子来更好地理解它。
代码 #1:
# Python code demonstrate creating
# DataFrame from dict narray / lists
# By default addresses.
import pandas as pd
# initialise data of lists.
data = {'Category':['Array', 'Stack', 'Queue'],
'Marks':[20, 21, 19]}
# Create DataFrame
df = pd.DataFrame(data)
# Print the output.
print(df )
输出:
Category Marks
0 Array 20
1 Stack 21
2 Queue 19
注意:要从narray/list的dict创建DataFrame,所有的narray必须是相同的长度。如果传递了索引,那么索引的长度应该等于数组的长度。如果没有传递索引,那么默认情况下,索引将是range(n),其中n是数组长度。
代码 #2:
# Python code demonstrate creating
# DataFrame from dict narray / lists
# By default addresses.
import pandas as pd
# initialise data of lists.
data = {'Category':['Array', 'Stack', 'Queue'],
'Student_1':[20, 21, 19], 'Student_2':[15, 20, 14]}
# Create DataFrame
df = pd.DataFrame(data)
# Print the output.
print(df.transpose())
输出:
0 1 2
Category Array Stack Queue
Student_1 20 21 19
Student_2 15 20 14
代码#3:为数据框架提供索引列表
# Python code demonstrate creating
# DataFrame from dict narray / lists
# By default addresses.
import pandas as pd
# initialise data of lists.
data = {'Area':['Array', 'Stack', 'Queue'],
'Student_1':[20, 21, 19], 'Student_2':[15, 20, 14]}
# Create DataFrame
df = pd.DataFrame(data, index =['Cat_1', 'Cat_2', 'Cat_3'])
# Print the output.
print(df)
输出:
Area Student_1 Student_2
Cat_1 Array 20 15
Cat_2 Stack 21 20
Cat_3 Queue 19 14