为什么 Pandas 数据帧中的单个行作为元组返回,为什么我的元组"broken"?



我在Pandas for Python3中使用不同的数据帧,这些数据帧包含不同的族关系。

示例数据帧如下所示:

 i         function  
0                                Anselm Franz Molitoris    Schwiegersohn   
1                                Anselm Franz Molitoris          Tochter   
2                                Anselm Franz Molitoris          Ehefrau   
3                                Anselm Franz Molitoris   Schwiegervater   
4                                Anselm Franz Molitoris          unknown   
...                                                 ...              ...   
1019                  Mauritius Ferdinand Anton Gudenus            Vater   
1020                  Mauritius Ferdinand Anton Gudenus           Mutter   
1021  Maria Magdalena Sidonia Gabriela Theresia Gudenus          Ehemann   
1022  Maria Magdalena Sidonia Gabriela Theresia Gudenus            Vater   
1023  Maria Magdalena Sidonia Gabriela Theresia Gudenus           Mutter   
                                    name ident  info  
0               Konrad Wilhelm Strecker     81  none  
1                          N. Molitoris    116  none  
2                    Maria Anna Gudenus   159   none  
3                 Johann Moritz Gudenus   231   none  
4                                         none  none  
...                                  ...   ...   ...  
1019             Daniel Morritz Gudenus    28   none  
1020   Anna Maria Barbara von Bielstein    364  none  
1021        Alexander Bernhard Strecker     75  none  
1022             Daniel Morritz Gudenus    28   none  
1023   Anna Maria Barbara von Bielstein    364  none   

因此它们有5列:ifunctionnameidentinfo

我使用这两行代码从选定的数据帧中读取一行并打印:

for child in df_sibling2.iterrows():
        print(child)

打印一行,我在控制台输出中得到这个:

(24, i           Konrad Wilhelm Strecker
function                       Sohn
name                 Karl Strecker 
ident                            79
info                           none
Name: 24, dtype: object)

在检查类时,Python告诉我该类型是元组。然而,有些地方显然是错误的,因为没有逗号分隔实际值,而且我的数据帧的头列是元组数据的一部分。

我最初是使用了错误的函数来读取单个行,还是存在其他问题?我需要单独的行才能将这些信息写入不同的Excel工作表,所以任何允许通过索引选择值的数据类型对我来说都很好。元组是可索引的,因此是完美的,但我现在得到的是一团糟。非常感谢您的帮助。

好消息:您的元组没有被破坏。

iterrows()的文档状态:

将DataFrame行作为(index,Series(对进行迭代。

此处"对";是指";长度为2〃的元组;。

文件进一步说明:

收益率:

index:标签或标签的元组

The index of the row. A tuple for a MultiIndex.

数据:系列

The data of the row as a Series.

当您调用print(child)时,您会看到一个长度为2的元组,其中包含24(行的索引值(作为其第一个元素,后跟逗号,,然后是该行中的相应数据,作为索引i, function, name, ident and info作为第二个值的Series。

根据您的问题:

我需要单独的行才能将这些信息写入不同的EXCEL表

上例中的单个行将是可作为child[1]访问的Series

如果您需要将整个数据帧写入Excel工作表,您可能还对DataFrameto_excel()方法感兴趣。例如,您可能决定将原始数据帧的行划分为多个数据帧,然后将每个数据帧写入不同的Excel表中。

.iterrows()返回由逗号分隔的2个元素的元组。第二个元素是Pandas对象,它有自己的显示表示。

简单示例:

>>> df = pd.DataFrame({"a":2, "b":3}, index=["x"])
>>> row = next(df.iterrows())
>>> row
('x', a    2
b    3
Name: x, dtype: int64)
>>> type(row)
<class 'tuple'>
>>> type(row[0])
<class 'str'>
>>> type(row[1])
<class 'pandas.core.series.Series'>

最新更新