如何将另一个数组中的字符串附加到Pandas数据框的列?

huangapple go评论95阅读模式
英文:

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

问题

我有一个类似下面的数据框:

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

我想要将从数组中选取的字符串附加到“ip”列,就像这样:

  1. arr = ["(0)", "(1)", "(2)", "(3)", "(4)", "(5)", "(6)", "(7)", "(8)"]
  2. ip metric
  3. 0 10.10.20.9(0) 0
  4. 1 10.10.1.25(1) 0
  5. 2 10.1.13.45(2) 0
  6. 3 10.1.100.101(3) 0
  7. 4 10.1.100.11(4) 0
  8. 5 10.11.2.100(5) 0
  9. 6 10.1.2.151(6) 0
  10. 7 10.1.2.184(7) 0
  11. 8 10.1.20.185(8) 0

你可以看到我从数组中取出了项目并添加到“ip”列的值中。

现在我知道如何将字符串添加到数据框的列中,可以像下面这样做:

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

但我无法弄清楚如何将数组中的项目添加到数据框列中。有什么方法可以做到这一点吗?

英文:

I have a Dataframe that looks like below

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

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

  1. arr = ["(0)", "(1)", "(2)", "(3)", "(4)", "(5)", "(6)", "(7)", "(8)"]
  2. ip metric
  3. 0 10.10.20.9(0) 0
  4. 1 10.10.1.25(1) 0
  5. 2 10.1.13.45(2) 0
  6. 3 10.1.100.101(3) 0
  7. 4 10.1.100.11(4) 0
  8. 5 10.11.2.100(5) 0
  9. 6 10.1.2.151(6) 0
  10. 7 10.1.2.184(7) 0
  11. 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

  1. 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长度相同,你可以拼接字符串:

  1. df['ip'] += arr
  2. print(df)
  3. # 输出
  4. ip metric
  5. 0 10.10.20.9(0) 0
  6. 1 10.10.1.25(1) 0
  7. 2 10.1.13.45(2) 0
  8. 3 10.1.100.101(3) 0
  9. 4 10.1.100.11(4) 0
  10. 5 10.11.2.100(5) 0
  11. 6 10.1.2.151(6) 0
  12. 7 10.1.2.184(7) 0
  13. 8 10.1.20.185(8) 0
英文:

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

  1. df['ip'] += arr
  2. print(df)
  3. # Output
  4. ip metric
  5. 0 10.10.20.9(0) 0
  6. 1 10.10.1.25(1) 0
  7. 2 10.1.13.45(2) 0
  8. 3 10.1.100.101(3) 0
  9. 4 10.1.100.11(4) 0
  10. 5 10.11.2.100(5) 0
  11. 6 10.1.2.151(6) 0
  12. 7 10.1.2.184(7) 0
  13. 8 10.1.20.185(8) 0

答案2

得分: -1

尝试使用lambda函数

  1. df['ip'] = df['ip'].apply(lambda x: str(x) + "%")
英文:

Try using a lambda function

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

huangapple
  • 本文由 发表于 2023年3月7日 13:21:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/75658285.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定