如何使用python使用函数中的值进行循环迭代?

2024-09-27 02:23:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在函数中使用循环逐个传递值python.值存储在数据帧中。你知道吗

def eam(A,B):
    y=A +" " +B
    return y

假设我将A的值作为country传递,B的值作为capital传递。 数据帧df

country                   capital
India                     New Delhi
Indonesia                 Jakarta
Islamic Republic of Iran  Tehran
Iraq                      Baghdad
Ireland                   Dublin

如何使用循环获取值

0   India New Delhi
1   Indonesia Jakarta
2   Islamic Republic of Iran Tehran
3   Iraq Baghdad
4   Ireland Dublin

Tags: of数据newcountryirancapitalindiatehran
1条回答
网友
1楼 · 发布于 2024-09-27 02:23:41

现在,只需使用以下语法在数据帧中获得一个新列。不需要编写代码来循环行。但是,如果必须循环,数据框箭头()返回或数据框itertuples()提供良好的功能来实现类似的目标。你知道吗

>>> df = pd.read_clipboard(sep='\t')
>>> df.head()
                    country    capital
0                     India  New Delhi
1                 Indonesia    Jakarta
2  Islamic Republic of Iran     Tehran
3                      Iraq    Baghdad
4                   Ireland     Dublin
>>> df.columns
Index(['country', 'capital'], dtype='object')
>>> df['both'] = df['country'] + " " + df['capital']
>>> df.head()
                    country    capital                             both
0                     India  New Delhi                  India New Delhi
1                 Indonesia    Jakarta                Indonesia Jakarta
2  Islamic Republic of Iran     Tehran  Islamic Republic of Iran Tehran
3                      Iraq    Baghdad                     Iraq Baghdad
4                   Ireland     Dublin                   Ireland Dublin

相关问题 更多 >

    热门问题