📌  相关文章
📜  使用列表创建 Pandas 数据框

📅  最后修改于: 2022-05-13 01:54:41.156000             🧑  作者: Mango

使用列表创建 Pandas 数据框

Pandas DataFrame 是一种二维标记数据结构,具有可能不同类型的列。它通常是最常用的 pandas 对象。
Pandas DataFrame 可以通过多种方式创建。让我们讨论如何使用列表创建 Pandas 数据框。

代码#1:

Python3
# Import pandas library
import pandas as pd
 
# initialize list of lists
data = [['Geeks', 10], ['for', 15], ['geeks', 20]]
 
# Create the pandas DataFrame
df = pd.DataFrame(data, columns = ['Name', 'Age'])
 
# print dataframe.
print(df )


Python3
# Import pandas library
import pandas as pd
 
# initialize list of lists
data = [['DS', 'Linked_list', 10], ['DS', 'Stack', 9], ['DS', 'Queue', 7],
        ['Algo', 'Greedy', 8], ['Algo', 'DP', 6], ['Algo', 'BackTrack', 5], ]
 
# Create the pandas DataFrame
df = pd.DataFrame(data, columns = ['Category', 'Name', 'Marks'])
 
# print dataframe.
print(df )


Python3
# Import pandas library
import pandas as pd
 
# initialize list of lists
data = [[1, 5, 10], [2, 6, 9], [3, 7, 8]]
 
# Create the pandas DataFrame
df = pd.DataFrame(data)
 
# specifying column names
df.columns = ['Col_1', 'Col_2', 'Col_3']
 
# print dataframe.
print(df, "\n")
 
# transpose of dataframe
df = df.transpose()
print("Transpose of above dataframe is-\n", df)


输出:
Name  Age
0  Geeks   10
1    for   15
2  geeks   20


代码#2:

Python3

# Import pandas library
import pandas as pd
 
# initialize list of lists
data = [['DS', 'Linked_list', 10], ['DS', 'Stack', 9], ['DS', 'Queue', 7],
        ['Algo', 'Greedy', 8], ['Algo', 'DP', 6], ['Algo', 'BackTrack', 5], ]
 
# Create the pandas DataFrame
df = pd.DataFrame(data, columns = ['Category', 'Name', 'Marks'])
 
# print dataframe.
print(df )
输出:
Category         Name  Marks
0       DS  Linked_list     10
1       DS        Stack      9
2       DS        Queue      7
3     Algo       Greedy      8
4     Algo           DP      6
5     Algo    BackTrack      5


代码#3:对数据框进行一些操作。

Python3

# Import pandas library
import pandas as pd
 
# initialize list of lists
data = [[1, 5, 10], [2, 6, 9], [3, 7, 8]]
 
# Create the pandas DataFrame
df = pd.DataFrame(data)
 
# specifying column names
df.columns = ['Col_1', 'Col_2', 'Col_3']
 
# print dataframe.
print(df, "\n")
 
# transpose of dataframe
df = df.transpose()
print("Transpose of above dataframe is-\n", df)
输出:
Col_1  Col_2  Col_3
0      1      5     10
1      2      6      9
2      3      7      8 

Transpose of above dataframe is-
         0  1  2
Col_1   1  2  3
Col_2   5  6  7
Col_3  10  9  8