Pandas将列表转换为dataframe

时间:2020-02-23 14:42:05  来源:igfitidea点击:

在本教程中,我们将看到从列表中创建Pandas DataFrame的不同方式。

我们可以使用 Dataframe()的方法 pandas库将列表转换为dataframe。
首先,我们必须使用导入语句将Pandas 库导入Python文件。

因此,让我们在创建与列表中创建DataFrame的各种示例:

示例1:使用列表创建DataFrame。

# Example 1 :
 
# import pandas package as pd in this code
import pandas as pd 
 
# give list of strings 
stringList = ["java","2","blog","dot","com"] 
 
# Convert the given list into pandas DataFrame 
df = pd.DataFrame(stringList) 
 
print(df)

输出 :

0
0  java
1     2
2  blog
3   dot
4   com

示例2:使用具有索引和列名称的列表创建DataFrame。

# import pandas as pd 
import pandas as pd 
 
# give list of strings 
stringList = ["java","2","blog","dot","com"]  
 
# Convert the given list into pandas DataFrame 
# with indices and column name specified 
df = pd.DataFrame(stringList, index =['a', 'b', 'c', 'd','e'], columns =['names']) 
 
print(df)

输出 :

names
a  java
b     2
c  blog
d   dot
e   com

示例3:使用zip()函数和列名的列表创建Dataframe。

# import pandas package as pd in this code
import pandas as pd 
 
# give list of strings   
stringList = ["java","2","blog","dot","com"]  
 
# give list of strings   
stringLenList = [4, 1, 4, 3, 3] 
 
# Convert the given two lists into DataFrame 
# after zipping both lists, with columns specified. 
df = pd.DataFrame(list(zip(stringList, stringLenList)), columns =['names', 'length']) 
 
print(df)

输出 :

names  length
0  java       4
1     2       1
2  blog       4
3   dot       3
4   com       3

示例4:使用列表和列名单创建DataFrame。

# import pandas package as pd in this code
import pandas as pd  
 
# given list of lists.   
lst = [['ankit', 22], ['rahul', 25], 
       ['priya', 27], ['golu', 22]] 
 
# Convert the given list of lists into pandas DataFrame     
df = pd.DataFrame(lst, columns =['Name', 'Age']) 
 
print(df)

输出 :

Name  Age
0  ankit   22
1  rahul   25
2  priya   27
3   golu   22

示例5:使用列表创建DataFrame作为字典中的值。

# import pandas package as pd in this code
import pandas as pd  
 
# list of name, degree, score 
name = ["ankit", "aishwarya", "priya", "Golu"] 
degree = ["btech", "btech", "mba", "bhms"] 
score = [90, 40, 80, 98] 
 
# dictionary of lists  
dict = {'name': name, 'degree': degree, 'score': score}  
 
# Convert the given dictionary into pandas DataFrame      
df = pd.DataFrame(dict) 
 
print(df)

输出 :

degree       name  score
0  btech      ankit     90
1  btech  aishwarya     40
2    mba      priya     80
3   bhms       Golu     98