📌  相关文章
📜  如何将 Pandas 系列转换为Python列表?

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

如何将 Pandas 系列转换为Python列表?

在本文中,我们将讨论如何将 Pandas 系列转换为Python列表及其类型。这可以使用 tolist() 方法来完成。
示例 1:

Python3
import pandas as pd
  
  
evenNumbers = [2, 4, 6, 8, 10]
  
evenNumbersDs = pd.Series(evenNumbers)
print("Pandas Series and type")
print(evenNumbersDs)
print(type(evenNumbersDs))
  
print("\nConvert Pandas Series to Python list")
print(evenNumbersDs.tolist())
print(type(evenNumbersDs.tolist()))


Python3
import pandas as pd
import numpy as np
  
  
data = np.array(['ant','bat','cat','dog'])
series = pd.Series(data,index=[100,101,102,103])
print(series)
print(type(series))
  
print("\nConvert Pandas Series to Python list")
print(series.tolist())
print(type(series.tolist()))


Python3
# Series from dictionary
import pandas as pd
import numpy as np
  
  
marks = {'Maths' : 100., 'Physics' : 90.,
         'Chemistry' : 85.}
series = pd.Series(marks)
  
print(series)
print(type(series))
  
print("\nConvert Pandas Series to Python list")
print(series.tolist())
print(type(series.tolist()))


Python3
# Get First 3 student marks and
# convert as list
import pandas as pd
series = pd.Series([100, 90, 80, 90, 85],
                   index=['Student1', 'Student2',
                          'Student3', 'Student4',
                          'Student5'])
  
# retrieve the first three element
print(series[:3])
print(series[:3].tolist())
print(type(series[:3].tolist()))


输出:

熊猫系列上市

在上面的示例中,我们将 Panda 系列数据作为 evenNumbers 传递。由于未给出索引,默认情况下为 0 采取
示例 2:

Python3

import pandas as pd
import numpy as np
  
  
data = np.array(['ant','bat','cat','dog'])
series = pd.Series(data,index=[100,101,102,103])
print(series)
print(type(series))
  
print("\nConvert Pandas Series to Python list")
print(series.tolist())
print(type(series.tolist()))

输出:

熊猫系列上市

在上面的示例中,我们将 Panda 系列数据作为 np.array(['ant','bat','cat','dog']) 传递。
索引为 [100,101,102,103]

示例 3:

Python3

# Series from dictionary
import pandas as pd
import numpy as np
  
  
marks = {'Maths' : 100., 'Physics' : 90.,
         'Chemistry' : 85.}
series = pd.Series(marks)
  
print(series)
print(type(series))
  
print("\nConvert Pandas Series to Python list")
print(series.tolist())
print(type(series.tolist()))

输出:

熊猫系列上市

示例 4:

Python3

# Get First 3 student marks and
# convert as list
import pandas as pd
series = pd.Series([100, 90, 80, 90, 85],
                   index=['Student1', 'Student2',
                          'Student3', 'Student4',
                          'Student5'])
  
# retrieve the first three element
print(series[:3])
print(series[:3].tolist())
print(type(series[:3].tolist()))

输出:

熊猫系列上市