在熊猫数据框中循环

时间:2020-02-17 12:04:15

标签: python pandas dataframe

我在熊猫中有以下数据框:

src_ch_id;src_ch_name;src_ch_desc;src_table_name
aa;q1;11;DataTable_4
bb;q2;22;DataTable_4
cc;q3;33;DataTable_4

使用此数据框,我将为数据库的每一行创建一个插入。为了测试,我将打印参数。

for index in channeldef_data_df:    
   src_ch_id = channeldef_data_df.iloc[[index], channeldef_data_df.columns.get_loc('src_ch_id')]
   print('--')
   print(src_ch_id)

我给出以下错误:

".iloc requires numeric indexers, got ['src_ch_id']"

我认为问题是代码中的[index]部分。我在循环中犯了什么错误?

2 个答案:

答案 0 :(得分:0)

使用pandas.DataFrame.iterrows将DataFrame行作为(索引,系列)对进行迭代。
for index, row in channeldef_data_df.iterrows():

>>> for index,_ in channeldef_data_df.iterrows():
...     src_ch_id = channeldef_data_df.iloc[[index], channeldef_data_df.columns.get_loc('src_ch_id')]
...     print(src_ch_id)
...
0    aa
Name: src_ch_id, dtype: object
1    bb
Name: src_ch_id, dtype: object
2    cc
Name: src_ch_id, dtype: object

您正在使用for index in channeldef_data_df:,它将仅在您的代码中返回列名称。

>>> for index in channeldef_data_df:
...     print(index)
...
src_ch_id
src_ch_name
src_ch_desc
src_table_name

答案 1 :(得分:0)

如果您只想提取src_ch_id并打印,也许可以使用itertuples()

for index in channeldef_data_df.itertuples():    
    src_ch_id = index.src_ch_id
    print('--')
    print(src_ch_id)

这样,您就可以为每一行获取src_ch_id