英文:
How to append strings to the column of a Dataframe from another array in Pandas?
问题
我有一个类似下面的数据框:
                    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
我想要将从数组中选取的字符串附加到“ip”列,就像这样:
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
你可以看到我从数组中取出了项目并添加到“ip”列的值中。
现在我知道如何将字符串添加到数据框的列中,可以像下面这样做:
df["ip"] = df["ip"].astype(str) + '%'
但我无法弄清楚如何将数组中的项目添加到数据框列中。有什么方法可以做到这一点吗?
英文:
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?
答案1
得分: 3
如你的数组与你的DataFrame长度相同,你可以拼接字符串:
df['ip'] += arr
print(df)
# 输出
                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
英文:
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
答案2
得分: -1
尝试使用lambda函数
df['ip'] = df['ip'].apply(lambda x: str(x) + "%")
英文:
Try using a lambda function
df['ip'] = df['ip'].apply(lambda x: str(x) + "%")
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论