Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/flash/4.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
Python 将列中的字符串替换为唯一的随机字符串_Python_String_Pandas_Csv_Random - Fatal编程技术网

Python 将列中的字符串替换为唯一的随机字符串

Python 将列中的字符串替换为唯一的随机字符串,python,string,pandas,csv,random,Python,String,Pandas,Csv,Random,我有一个csv,它有多个列,其中一列由字符串组成 我首先读取csv文件,然后使用两列 df = pd.read_csv("MyDATA_otherstring.csv", usecols=["describe_file", "data_numbers"]) 这是输出 describe_file data_numbers 0 This is the start of the story 7309.0 1 This is the start of the story 35.

我有一个csv,它有多个列,其中一列由字符串组成

我首先读取csv文件,然后使用两列

df = pd.read_csv("MyDATA_otherstring.csv", usecols=["describe_file", "data_numbers"])
这是输出

    describe_file   data_numbers
0   This is the start of the story  7309.0
1   This is the start of the story  35.0
2   This is the start of the story  302.0
3   Difficult part  7508.5
4   Difficult part  363.0
在大约10k行中,大约有150个独特的字符串。这些字符串在文件中出现多次

我的目标 按第一个字符串示例“这是故事的开始”进行筛选,并将其替换为随机字符串

我想运行该列中的所有字符串,并用唯一的字符串替换它们

我已经查看了random library和这里提出的一些问题,不幸的是,我没有找到任何对我有帮助的东西。

这是您的示例:

import pandas as pd
import numpy as np
from string import ascii_lowercase

df = pd.DataFrame([['This is the start of the story']*3 + ['Difficult part']*2, 
    np.random.rand(5)], index=['describe_file', 'data_numbers']).T
这就是你可以做到的:

df.describe_file = df.join(df.groupby('describe_file')['describe_file'].apply(lambda x:
    ''.join(np.random.choice(list(ascii_lowercase), 10))), \
    on='describe_file', rsuffix='_NEW')['describe_file_NEW']
结果是:

  describe_file data_numbers
0    skgfdrsktw     0.204907
1    skgfdrsktw     0.399947
2    skgfdrsktw     0.990196
3    rziuoslpqn     0.930852
4    rziuoslpqn     0.210122

@Nicolas Gervais之前的回答很好,但在多次阅读该问题后,我解释该问题是用随机字符串替换“这是故事的一部分”,但保留其余“困难部分”。下面的命令(包括
.replace()
语句)正在执行此操作

df['describe_file'].apply(lambda x: x.replace('This is the start of the story', ''.join(np.random.choice(list(ascii_lowercase), 10)))) 

谢谢你的回答,不过我正试图找到一些可以用所有字符串来实现这一点的方法。如果我必须处理并粘贴到代码中的每个字符串。除了像这样在Excels中执行查找和替换选项之外,我不会再安全了?(见答案)。i、 例如,为整个专栏制作随机字符串?而“字符串”这是故事的开始“应该替换为一个强字符串,而不是每次不同的字符串。所有“这是故事的开始”替换为“kkbim”。所有“困难部分”都替换为其他字符串。希望这是您所期望的(请参见编辑)请更具体地说明你做了哪些研究,你做了哪些尝试。你至少可以以更方便或实用的格式提供数据。
df['describe_file'].apply(lambda x: x.replace('This is the start of the story', ''.join(np.random.choice(list(ascii_lowercase), 10)))) 
0        glhrtqwlnl
1        qxrklnxhoj
2        kszgtysptj
3    Difficult part
4    Difficult part
Name: describe_file, dtype: object