【问题标题】:How to classify the same index如何对相同的索引进行分类
【发布时间】:2021-11-10 03:27:03
【问题描述】:

我有两个pandas.DataFrame的表单

两个数据框是:

df1 = pd.DataFrame(4*[100,100,100],4*[0,1,2])
df2 = pd.DataFrame([1,2,3,4,5,6,7,8,9],[0,1,2,0,1,0,2,1,2])

我想根据 df1 的索引,用相同的索引对 df1 和 df2 进行分类。 我想把 0 放在空白处。 这是我的预期结果:

index     df1       df2

0         100       1
1         100       2
2         100       3
0         100       4
1         100       5
2         100       0
0         100       6
1         100       0
2         100       7
0         100       0
1         100       8
2         100       9

这可能吗?

【问题讨论】:

    标签: python sorting indexing classification


    【解决方案1】:

    如果你不介意索引,比如这种格式,:

    Int64Index([0, 0, 0, 1, 1, 1, 2, 2, 2], dtype='int64')
    

    你可以试试这个:

    new_df = pd.merge(df1, df2, left_index=True, right_index=True, how='right').drop_duplicates()
    new_df.rename(columns={'0_x' : 'df1',
                           '0_y' : 'df2'})
    

    它会给你:

       df1  df2
    0  100    1
    0  100    4
    0  100    6
    1  100    2
    1  100    5
    1  100    8
    2  100    3
    2  100    7
    2  100    9
    

    【讨论】:

      【解决方案2】:

      我想你要找的是pandas.DataFrame.sort_values

      参考the official documentation

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-03-16
        • 1970-01-01
        • 2013-06-09
        • 1970-01-01
        • 2022-12-18
        • 2022-07-05
        • 2020-09-02
        相关资源
        最近更新 更多