0

I want to pass values using loop one by one in function using python.Values are stored in dataframe.

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

Suppose I pass the values of A as country and B as capital . Dataframe df is

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

How can I get value using loop

0   India New Delhi
1   Indonesia Jakarta
2   Islamic Republic of Iran Tehran
3   Iraq Baghdad
4   Ireland Dublin
4
  • If your data frame a Pandas DataFrame? Commented Jan 18, 2018 at 16:26
  • If you really want a loop, you could use apply() like this: df.apply(lambda x: eam(x['country'], x['capital']), axis=1) Commented Jan 18, 2018 at 16:31
  • Why was this tagged as regex? Commented Jan 18, 2018 at 16:33
  • yes,dataframe is pandas DataFrame Commented Jan 18, 2018 at 16:45

1 Answer 1

1

Here you go, just use the following syntax to get a new column in the dataframe. No need to write code to loop over the rows. However, if you must loop, df.iterrows() returns or df.itertuples() provide nice functionality to accomplish similar objectives.

>>> 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
Sign up to request clarification or add additional context in comments.

1 Comment

The values need to be passed in function eam. Dont use directly dataframe

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.