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

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

如何将字典转换为 Pandas 系列?

让我们讨论如何在Python中将字典转换为pandas 系列。系列是一维标记数组,可以包含任何类型的数据,即整数、浮点数、字符串、 Python对象等,而字典是键:值对的无序集合。我们使用 pandas 库的series()函数通过将字典作为参数传递来将字典转换为系列。

让我们看一些例子:

示例 1:我们将字典名称作为参数传递给 series()函数。输出顺序将与字典相同。

Python3
# Import pandas library
import pandas as pd
 
# Create a dictionary
d = {'g' : 100, 'e' : 200,
     'k' : 400, 's' : 800,
     'n' : 1600}
 
# Convert from dictionary to series
result_series = pd.Series(d)
 
# Print series
result_series


Python3
# Import pandas library
import pandas as pd
 
# Create a dictionary
d = {'a' : 10, 'b' : 20,
     'c' : 40, 'd' :80,
     'e' :160}
 
  
# Convert from dictionary to series
result_series = pd.Series(d, index = ['e', 'b',
                                      'd', 'a',
                                      'c'])
# Print series
result_series


Python3
# Import pandas library
import pandas as pd
 
# Create a dictionary
d = {'a' : 10, 'b' : 20,
     'c' : 40, 'd':80}
 
# Convert from dictionary to series
result_series = pd.Series(d, index = ['b', 'd',
                                      'e', 'a',
                                      'c'])
# Print series
result_series


输出:

示例 2:我们传递字典的名称和不同的索引顺序。输出的顺序将与我们在参数中传递的顺序相同。

Python3

# Import pandas library
import pandas as pd
 
# Create a dictionary
d = {'a' : 10, 'b' : 20,
     'c' : 40, 'd' :80,
     'e' :160}
 
  
# Convert from dictionary to series
result_series = pd.Series(d, index = ['e', 'b',
                                      'd', 'a',
                                      'c'])
# Print series
result_series

输出:

示例 3:在上面的示例中,索引列表的长度与字典中的键数相同。如果它们不相等会发生什么让我们通过一个例子来看看。

Python3

# Import pandas library
import pandas as pd
 
# Create a dictionary
d = {'a' : 10, 'b' : 20,
     'c' : 40, 'd':80}
 
# Convert from dictionary to series
result_series = pd.Series(d, index = ['b', 'd',
                                      'e', 'a',
                                      'c'])
# Print series
result_series

输出:

所以它将 NaN 值分配给相应的索引。