我有一个pandas数据帧,其中包含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)
但上述方法不可行。我想保留所有以“one”或“two”开头的内容。
有什么好的思路来实现吗?我的数据集非常庞大,因此效率是很重要的。
dx1-dx99
或px1-px99
? - Divakarnumpy.in1d
的文档:https://dev59.com/QWIk5IYBdhLWcg3wI7EF https://docs.scipy.org/doc/numpy/reference/generated/numpy.in1d.html - Chuck