How to append strings to the column of a Dataframe from another array in Pandas?

Question:

I have a Dataframe that looks like below

                ip  metric
0       10.10.20.9       0
1       10.10.1.25       0
2       10.1.13.45       0
3     10.1.100.101       0
4      10.1.100.11       0
5      10.11.2.100       0
6       10.1.2.151       0
7       10.1.2.184       0
8      10.1.20.185       0

I want to append some strings to the ip column picked from an array like so

arr = ["(0)", "(1)", "(2)", "(3)", "(4)", "(5)", "(6)", "(7)", "(8)"]

                ip  metric
0    10.10.20.9(0)       0
1    10.10.1.25(1)       0
2    10.1.13.45(2)       0
3  10.1.100.101(3)       0
4   10.1.100.11(4)       0
5   10.11.2.100(5)       0
6    10.1.2.151(6)       0
7    10.1.2.184(7)       0
8   10.1.20.185(8)       0

You can see I took items from the array and added to the values of the ip column.

Now I know how to add a string to the column of a Dataframe by doing something like below

df["ip"] = df["ip"].astype(str) + '%'

But I can’t figure out how to add items from an array to the Dataframe column. Any idea how this can be done?

Asked By: Souvik Ray

||

Answers:

Try using a lambda function

df['ip'] = df['ip'].apply(lambda x: str(x) + "%")
Answered By: Colonel_Old

As your array has the same length of your DataFrame, you can concatenate strings:

df['ip'] += arr
print(df)

# Output
                ip  metric
0    10.10.20.9(0)       0
1    10.10.1.25(1)       0
2    10.1.13.45(2)       0
3  10.1.100.101(3)       0
4   10.1.100.11(4)       0
5   10.11.2.100(5)       0
6    10.1.2.151(6)       0
7    10.1.2.184(7)       0
8   10.1.20.185(8)       0
Answered By: Corralien

You can use pop to pop out the elements in the array and in case the array elements are less than the df observations you can add if-else statement just in case.

df['ip'] = df['ip'].apply(lambda x: str(x) + arr.pop(0) if arr else str(x))
Answered By: Strikoder
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.