根据列表中的部分字符串过滤熊猫(python)数据帧

我有一个99列dx1-dx99&列的熊猫数据框. px1-px99的99列.这些列的内容是长度为4到8个字符及以上的代码.数字.

我只想从这些列中过滤那些内容,其中这些内容的前三个字符与提供的列表中的三个字符匹配.提供的列表包含仅包含三个字符的字符串.

我动态生成的提供列表的长度非常长.因此,我必须将整个列表而不是作为单独的字符串传递.

例如,我有以下数据框:

df = pd.DataFrame({'A': 'foo bar one123 bar foo one324 foo 0'.split(),
                   'B': 'one546 one765 twosde three twowef two234 onedfr three'.split(),
                   'C': np.arange(8), 'D': np.arange(8) * 2})
    print(df)

        A       B  C   D
0     foo  one546  0   0
1       0  one765  1   2
2  one123  twosde  2   4
3     bar   three  3   6
4     foo  twowef  4   8
5  one324  two234  5  10
6     foo  onedfr  6  12
7       0   three  7  14

填充的单元格是对象类型,所有零最初都是NULL,我通过pd.fillna(0)用零填充了这些零.

当我这样做时:

keep = df.iloc[:,:].isin(['one123','one324','twosde','two234']).values
df.iloc[:,:] = df.iloc[:,:].where(keep, 0)
print(df)

我懂了:

        A       B  C  D
0       0       0  0  0
1       0       0  0  0
2  one123  twosde  0  0
3       0       0  0  0
4       0       0  0  0
5  one324  two234  0  0
6       0       0  0  0
7       0       0  0  0

但是,我不想传递单个字符串’one123′,’one324′,’twosde’,’two234′,而是要传递包含这样的部分字符串的列表:

startstrings = ['one', 'two']

keep = df.iloc[:,:].contains(startstrings)
df.iloc[:,:] = df.iloc[:,:].where(keep, 0)
print(df)

但是上面是行不通的.我要保留所有以“一个”或“两个”开头的内容.

任何想法如何实施?我的数据集很大,因此效率很重要.

解决方法:

pandas str.contains接受正则表达式,让您测试列表中的任何项目.遍历每一列并使用str.contains:

startstrings = ['one', 'two']
pattern = '|'.join(startstrings)

for col in df:
    if all(df[col].apply(type) == str):
        #Set any values to 0 if they don't contain value
        df.ix[~df[col].str.contains(pattern), col] = 0        
    else:
        #Column is not all strings
        df[col] = 0

产生:

      A     B  C  D
0     0  one1  0  0
1     0  one1  0  0
2  one1  two1  0  0
3     0     0  0  0
4     0  two1  0  0
5  one1  two1  0  0
6     0  one1  0  0
7     0     0  0  0

相关文章

转载:一文讲述Pandas库的数据读取、数据获取、数据拼接、数...
Pandas是一个开源的第三方Python库,从Numpy和Matplotlib的基...
整体流程登录天池在线编程环境导入pandas和xrld操作EXCEL文件...
 一、numpy小结             二、pandas2.1为...
1、时间偏移DateOffset对象DateOffset类似于时间差Timedelta...
1、pandas内置样式空值高亮highlight_null最大最小值高亮背景...