嗨,我有一个 pd 数据帧列表(其中 1377 个)。我需要将每个数据帧拆分为行索引以 a 结尾和行索引以 c 结尾的情况。
我查看了其他建议这样做的堆栈溢出页面
(df.iloc[all_dfs[0].index.str.endswith('a',na=False)])
但是,这会转置我的数据帧,然后减少行数(转置之前的列数)
如果有帮助的话,这是我的第一个数据帧的一小部分。
最佳答案
您可以将测试值元组传递给 str.endswith
与 boolean indexing
用于过滤:
df = pd.DataFrame({'a':range(5)},
index=['_E031a','_E031b','_E031c','_E032a','_E032b'])
df1 = df[df.index.str.endswith(('a', 'c'),na=False)]
print (df1)
a
_E031a 0
_E031c 2
_E032a 3
或者通过索引[-1]
获取字符串的最后一个值,并通过Index.isin
测试成员资格:
df1 = df[df.index.str[-1].isin(['a', 'c'])]
print (df1)
a
_E031a 0
_E031c 2
_E032a 3
对于 DataFrame 列表中的循环,请使用:
all_dfs = [df[df.index.str.endswith(('a', 'c'),na=False)] for df in all_dfs]
如果只想测试a
:
all_dfs = [df[df.index.str.endswith('a',na=False)] for df in all_dfs]
关于python - 过滤 pandas 数据帧列表以仅包含以 a 结尾的行索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59703481/