Python-熊猫-仅删除仅包含数字的拆分,但如果包含字母则保留

时间:2020-02-12 17:20:17

标签: python regex string pandas

我有一个具有两个值的数据框:

import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import pyplot as plt
from matplotlib import pyplot as plt
import numpy as np

df = pd.read_csv(r'C:/Users/output.csv', delimiter=";", encoding='unicode_escape')
df['Plot_column'] = df['Plot_column'].str.split(',').str[0]
df['Plot_column'] = df['Plot_column'].astype('int64', copy=False)

X=df[df['goal_colum']=='start running']['Plot_column'].values


dev_x= X
mean_=np.mean(dev_x)
median_=np.median(dev_x)
standard_=np.std(dev_x)

plt.hist(dev_x, bins=5)
plt.plot(mean_, label='Mean')
plt.plot(median_, label='Median')
plt.plot(standard_, label='Std Deviation')



plt.title('Data')

我要执行的操作是在split('_')仅包含数字的情况下删除数字。 所需的输出是:

df = pd.DataFrame({'Col1': ['Table_A112', 'Table_A_112']})

为此,我正在使用以下代码:

Table_A112
Table_A_

但这给了我以下输出:

import pandas as pd
import difflib
from tabulate import tabulate
import string

df = pd.DataFrame({'Col1': ['Table_A112', 'Table_A_112']})
print(tabulate(df, headers='keys', tablefmt='psql'))
df['Col2'] = df['Col1'].str.rstrip(string.digits)
print(tabulate(df, headers='keys', tablefmt='psql'))

我该怎么办?

谢谢!

4 个答案:

答案 0 :(得分:5)

您可以执行以下操作:

s = df['Col1'].str.split('_',expand=True).stack()
s.mask(s.str.isdigit(), '').groupby(level=0).agg('_'.join)

输出:

0    Table_A112
1      Table_A_
dtype: object

答案 1 :(得分:4)

这是使用str.replace的一种方法:

df = pd.DataFrame({'Col1': ['Table_A112', 'Table_A_112', 'Table_112_avs']})

print(df)

        Col1
0     Table_A112
1    Table_A_112
2  Table_112_avs

df.Col1.str.replace(r'(?:^|_)(\d+)(?:$|_)', '_', regex=True)

0    Table_A112
1      Table_A_
2     Table_avs
Name: Col1, dtype: object

请参见demo

答案 2 :(得分:1)

如果您坚持使用正则表达式解决方案,则可以使用pandas.replace()r'(?<=_)\d+'后面的积极表情

import pandas as pd
from tabulate import tabulate

df = pd.DataFrame({'Col1': ['Table_A112', 'Table_A_112']})
print(tabulate(df, headers='keys', tablefmt='psql'))
df= df.replace(regex=r'(?<=_)\d+', value='')
print(tabulate(df, headers='keys', tablefmt='psql'))

将产生所需的输出。

答案 3 :(得分:0)

我认为将Destination:=与捕获组配合使用会使模式更加简单

str.replace