Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/309.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_Pandas_String - Fatal编程技术网

Python 列内的字符串操作(熊猫):拆分、替换、联接

Python 列内的字符串操作(熊猫):拆分、替换、联接,python,pandas,string,Python,Pandas,String,我想根据以下条件创建一个新列: 如果行包含dogs/dog/chien/chien,则添加-00 如果该行包含cat/cat/chat/chats,则添加00- 数据样本如下: Animal 22 dogs 1 dog 1 cat 3 dogs 32 chats 到目前为止 我希望输出一个只有数字的列(数字): 我想我应该使用if条件来检查单词,然后.split和.join。这是关于字符串操作的,但我很难解决这个问题 您可以这样做,首先提取数字,然后使用np。其中有条件地向字符串添加字

我想根据以下条件创建一个新列:

  • 如果行包含dogs/dog/chien/chien,则添加-00
  • 如果该行包含cat/cat/chat/chats,则添加00-
数据样本如下:

Animal 

22 dogs
1 dog
1 cat
3 dogs
32 chats
到目前为止

我希望输出一个只有数字的列(数字):


我想我应该使用
if
条件来检查单词,然后
.split
.join
。这是关于字符串操作的,但我很难解决这个问题

您可以这样做,首先提取数字,然后使用
np。其中
有条件地向字符串添加字符:

df['New Col'] = df['Animal'].str.extract(r'([0-9]*)')
df['New Col'] = np.where(df['Animal'].str.contains('dogs|dog|chiens|chien'), df['New Col']+'-00', df['New Col'])
df['New Col'] = np.where(df['Animal'].str.contains('cats|cat|chat|chats'), '00-'+df['New Col'], df['New Col'])
print(df)

     Animal New Col
0   22 dogs   22-00
1     1 dog    1-00
2     1 cat    00-1
3    3 dogs    3-00
4  32 chats   00-32

可以这样做,首先提取数字,然后使用
np。其中
有条件地向字符串添加字符:

df['New Col'] = df['Animal'].str.extract(r'([0-9]*)')
df['New Col'] = np.where(df['Animal'].str.contains('dogs|dog|chiens|chien'), df['New Col']+'-00', df['New Col'])
df['New Col'] = np.where(df['Animal'].str.contains('cats|cat|chat|chats'), '00-'+df['New Col'], df['New Col'])
print(df)

     Animal New Col
0   22 dogs   22-00
1     1 dog    1-00
2     1 cat    00-1
3    3 dogs    3-00
4  32 chats   00-32
其中,
df
是您的数据帧。为了快速查找,我们将条件列表转换为集合。然后我们对
df
Animal
列的值应用一个函数,并相应地采取行动


其中,
df
是您的数据帧。为了快速查找,我们将条件列表转换为集合。然后我们对
df
Animal
列的值应用一个函数,并相应地采取行动

由于数据格式良好,您可以使用基本替换并将其应用于行:

import pandas as pd
import re

def replacer(s):
    return re.sub(r" (chiens?|dogs?)", "-00", 
                  re.sub(r"(\d+) ch?ats?", r"00-\1", s))

df = pd.DataFrame({"Animal": ["22 dogs", "1 dog", "1 cat", "3 dogs", "32 chats"]})
df["New Column"] = df["Animal"].apply(replacer)
输出:

     Animal New_col
0   22 dogs   22-00
1     1 dog    1-00
2     1 cat    00-1
3    3 dogs    3-00
4  32 chats   00-32
Animal新栏目
0 22只狗22-00
1只狗1-00
2 1类00-1
3只狗3-00
4 32聊天00-32

由于数据格式良好,您可以使用基本替换并将其应用于行:

import pandas as pd
import re

def replacer(s):
    return re.sub(r" (chiens?|dogs?)", "-00", 
                  re.sub(r"(\d+) ch?ats?", r"00-\1", s))

df = pd.DataFrame({"Animal": ["22 dogs", "1 dog", "1 cat", "3 dogs", "32 chats"]})
df["New Column"] = df["Animal"].apply(replacer)
输出:

     Animal New_col
0   22 dogs   22-00
1     1 dog    1-00
2     1 cat    00-1
3    3 dogs    3-00
4  32 chats   00-32
Animal新栏目
0 22只狗22-00
1只狗1-00
2 1类00-1
3只狗3-00
4 32聊天00-32
使用re:

import re

list1 = ['dogs', 'dog', 'chien', 'chiens']
list2 = ['cats', 'cat', 'chat', 'chats']

df['New_col'] = [(re.search(r'(\w+)', val).group(1).strip()+"-00") if re.search(r'([a-zA-Z]+)', val).group(1).strip() in list1 else ("00-" + re.search(r'(\w+)', val).group(1).strip()) if re.search(r'([a-zA-Z]+)', val).group(1).strip() in list2 else val for val in list(df['Animal'])]

print(df)
输出:

     Animal New_col
0   22 dogs   22-00
1     1 dog    1-00
2     1 cat    00-1
3    3 dogs    3-00
4  32 chats   00-32
使用re:

import re

list1 = ['dogs', 'dog', 'chien', 'chiens']
list2 = ['cats', 'cat', 'chat', 'chats']

df['New_col'] = [(re.search(r'(\w+)', val).group(1).strip()+"-00") if re.search(r'([a-zA-Z]+)', val).group(1).strip() in list1 else ("00-" + re.search(r'(\w+)', val).group(1).strip()) if re.search(r'([a-zA-Z]+)', val).group(1).strip() in list2 else val for val in list(df['Animal'])]

print(df)
输出:

     Animal New_col
0   22 dogs   22-00
1     1 dog    1-00
2     1 cat    00-1
3    3 dogs    3-00
4  32 chats   00-32

创建搜索词的元组

dog = ('dogs', 'dog', 'chien', 'chiens')
cat = ('cats', 'cat', 'chat', 'chats')
为使用相应替换创建的每个元组创建条件,并使用将条件应用于列:

num = df.Animal.str.split().str[0] #the numbers
#conditions
cond1 = df.Animal.str.endswith(dog)        
cond2 = df.Animal.str.endswith(cat)
condlist = [cond1,cond2]
#what should be returned for each successful condition
choicelist = [num+"-00","00-"+num]

df['New Column'] = np.select(condlist,choicelist)
df

    Animal    New Column
0   22 dogs     22-00
1   1 dog       1-00
2   1 cat       00-1
3   3 dogs      3-00
4   32 chats    00-32

创建搜索词的元组

dog = ('dogs', 'dog', 'chien', 'chiens')
cat = ('cats', 'cat', 'chat', 'chats')
为使用相应替换创建的每个元组创建条件,并使用将条件应用于列:

num = df.Animal.str.split().str[0] #the numbers
#conditions
cond1 = df.Animal.str.endswith(dog)        
cond2 = df.Animal.str.endswith(cat)
condlist = [cond1,cond2]
#what should be returned for each successful condition
choicelist = [num+"-00","00-"+num]

df['New Column'] = np.select(condlist,choicelist)
df

    Animal    New Column
0   22 dogs     22-00
1   1 dog       1-00
2   1 cat       00-1
3   3 dogs      3-00
4   32 chats    00-32

您的示例数据是否总是以
^\d+\w+$
的形式出现,或者
等是否可以在任意上下文中出现?换句话说,
“dogville中有22只猫”
是一个可能的单元格值吗?如果是,应该如何处理它?不,它应该是数字+字符串/特征的格式。您的样本数据总是以
^\d+\w+$
的形式出现,或者
等可以在任意上下文中出现?换句话说,
“dogville中有22只猫”
是一个可能的单元格值吗?如果是,应该如何处理它?不,应该是数字+字符串/字符的格式