我有一个带有99列dx1-dx99和99列px1-px99的熊猫数据框。这些列的内容是长度为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)
但是上面是行不通的。我要保留所有以“一个”或“两个”开头的内容。
任何想法如何实施?我的数据集很大,因此效率很重要。
大熊猫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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句