Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/cmake/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Pandas 我想使用循环在列中随机添加a到z。如何才能做到这一点?_Pandas_Dataset_Rows - Fatal编程技术网

Pandas 我想使用循环在列中随机添加a到z。如何才能做到这一点?

Pandas 我想使用循环在列中随机添加a到z。如何才能做到这一点?,pandas,dataset,rows,Pandas,Dataset,Rows,我想使用循环在列中随机添加a到z。如何才能做到这一点 I want to add randomly a to z in columns using loops.how can i do this? example: this my columns name 0 Tim 1 Mit 2 Jason 3 Jasim 4 Sible Expected results: name 0 Tima 1 Mitb 2 Jasonc 3

我想使用循环在列中随机添加a到z。如何才能做到这一点

I want to add randomly a to z in columns using loops.how can i do this? example: this my columns name 0 Tim 1 Mit 2 Jason 3 Jasim 4 Sible Expected results: name 0 Tima 1 Mitb 2 Jasonc 3 Jasim 4 Siblex 使现代化
我不会在这里使用循环;在.apply调用中使用lambda函数可以得到相同的结果。apply对数据的每一行执行相同的函数,lambdas允许您创建匿名函数

如果您有一个包含所有要添加的字母的字符串,则可以使用随机模块中的选择函数随机选择一个字母并将其添加到字符串中

lambda函数如下所示:lambda x:x+choiceleters。本质上,它表示对于任何值x,它将返回x加上随机选择的字母

假设您的名称列称为data,下面是上述示例:

from random import choice

letters = "abcdefghijklmnopqrstuvwxyz"

data.apply(lambda x: x + choice(letters))

我想给出一个范围。我该怎么做?@tosifulislam你说的范围是什么意思?假设我的列有1000个数据。我只想在200个数据中随机添加字母。地址列是什么?您的示例df只有名称,但这将适用于任何数据类型为stringmy address columns也是stringmy address columns但我想在我的数据中随机添加字母。但是您的代码将字母添加到我的所有数据中。然后最好的解决方案是上面Chris的回答。
import numpy as np
import string
# create a list of characters
choice_list = list(string.ascii_lowercase)

# create a rand sample of your dataframe
random_sample = df['name'].sample(3) # your sample size

# generate sudo random letter from the list    
rand = np.random.choice(choice_list, len(random_sample))

# append strings using iloc
df.iloc[random_sample.index, 0] = random_sample.values + rand


     name
0    Timy
1    Mitp
2  Jasony
3   Jasim
4   Sible
from random import choice

letters = "abcdefghijklmnopqrstuvwxyz"

data.apply(lambda x: x + choice(letters))