python - 如何删除列表形式的数据帧的重复索引?

标签 python pandas indexing duplicates

我有一个列表,其中每个元素都是 Dataframe 本身。这些 Dfs 具有重复的日期时间索引。我想删除该列表中每个 Df 的每个重复索引。


list_dfs = [df_1, df_2, df_3, df_4]

dtype='datetime64[ns]'  #Index of all Dfs in list_dfs

我正在使用这个列表理解代码。它正在删除重复的索引,但也删除了列。最后我只得到了索引。

[df.index.drop_duplicates(keep='last') for df in list_dfs]

知道如何实现这一目标吗?

最佳答案

使用Index.duplicated通过 boolean indexing 进行过滤和 ~ 用于反转 bool 掩码:

df = pd.DataFrame({
        'A':list('abcdef'),
         'F':list('aaabbb')
}).set_index('F')

df1 = pd.DataFrame({
        'A':list('tyuio'),
         'F':list('rrffv')
}).set_index('F')


list_dfs = [df, df1]

L = [df[~df.index.duplicated(keep='last')] for df in list_dfs]

print (L)
[   A
F   
a  c
b  f,    A
F   
r  y
f  i
v  o]

关于python - 如何删除列表形式的数据帧的重复索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59050023/

相关文章:

python - Pandas 数据帧 : count number of string value is in row for specific ID

sql - 在 postgres 中有效地标记行的连续子集

MySQL 不使用索引;使用文件排序

postgresql - 如何提高 postgres 查询的选择速度?

python - 如何融化数据框以获取范围内的所有日期?

python - 相同条件日期 True with Series 但 False using element

python - 当 n_jobs>1 时,scikit-learn 的 GridSearchCV 停止工作

python re找不到这个分组名称

python - 如何使用 Python websockets 库在 "pong"调用上获取 "ping"响应?

python - python3中的多处理在mac和linux上运行时得到不同的值