如果第二列与给定列表匹配,则替换dataframe列中的值

2024-06-28 19:06:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下数据帧

      col1          col2
0     str9          val1
1     str8          val2
2     str4          val3
3     str2          val4
4  unknown1    asdvstr1df
5  random1  teststr2test

下面的列表

strings = ['str1', 'str2', 'str3', 'str4']

如果第二列中的字符串中的任何一点与给定的列表strings匹配,我想替换第1列中的值。你知道吗

注意:col2可以在字符串内部或在字符串的任意一端包含列表“string”的值。你知道吗

目前,我正在使用一个丑陋而缓慢的嵌套循环:

import pandas as pd

data_file = pd.DataFrame(data = ([['str9', 'val1'], ['str8',  'val2'], ['str4','val3'] , ['str2', 'val4'] , ['unknown', 'asdvstr1df'] , ['unknown', 'teststr2test']] ), columns = (['col1', 'col2']), dtype = str)
strings = ['str1', 'str2', 'str3', 'str4']

for value in range(data_file.shape[0]):
    for text in strings:
        if (str(data_file.col2[value]).find(text) != -1):
            data_file.loc[value, 'col1'] = text

我不知道如何改进这个缓慢的过程。如何使其运行速度比当前的O(nm)时间快(n是数据文件的大小,m是称为字符串的列表的大小)?你知道吗

输出应为:

   col1          col2
0  str9          val1
1  str8          val2
2  str4          val3
3  str2          val4
4  str1    asdvstr1df
5  str2  teststr2test

Tags: 字符串列表datafilecol2col1stringsval1
3条回答

试试这个:

data_file["col1"] = data_file["col2"].apply(lambda y:strings[[True if x in y 
else False for x in strings ].index(True)] if any([True if x in y else False 
for x in strings ]) else y)
print(data_file)

输出:

   col1          col2
0  val1          val1
1  val2          val2
2  val3          val3
3  val4          val4
4  str1    asdvstr1df
5  str2  teststr2test

可以使用replace两次regex

d1=dict(zip(strings,[1,2,3,4]))
d2=dict(zip([1,2,3,4],strings))

df.loc[df.col1=='unknown','col1']=df.col2.replace(d1,regex=True).replace(d2)
df
Out[970]: 
   col1          col2
0  str9          val1
1  str8          val2
2  str4          val3
3  str2          val4
4  str1    asdvstr1df
5  str2  teststr2test

IIUC公司

x = '(' + '|'.join(strings)+ ')'
df.assign(col1 = df.col2.str.extract(x, expand=False).combine_first(df.col1))

输出:

   col1          col2
0  str9          val1
1  str8          val2
2  str4          val3
3  str2          val4
4  str1    asdvstr1df
5  str2  teststr2test

相关问题 更多 >