1

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?

Souvik Ray
  • 2,899
  • 5
  • 38
  • 70
  • Does this answer your question? [String concatenation of two pandas columns](https://stackoverflow.com/questions/11858472/string-concatenation-of-two-pandas-columns). Especially https://stackoverflow.com/a/11858532/2954547. – shadowtalker Mar 07 '23 at 05:41

2 Answers2

3

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
Corralien
  • 109,409
  • 8
  • 28
  • 52
-1

Try using a lambda function

df['ip'] = df['ip'].apply(lambda x: str(x) + "%")
Colonel_Old
  • 852
  • 9
  • 15