Python Pandas中的重复索引来自字典列表

4

我有一个包含两个键的字典列表。第一个键是共享索引,第二个键是列名。我想将这个列表转换为Pandas DataFrame对象。但是当我这样做时,我会得到重复的索引行,并且每行都有一个空列。

使用以下代码:

import pandas as pd
l = [{'col_a': 0, 'idx': 0},
     {'col_b': 5, 'idx': 0},
     {'col_a': 1, 'idx': 1},
     {'col_b': 6, 'idx': 1},
     {'col_a': 2, 'idx': 2},
     {'col_b': 7, 'idx': 2},
     {'col_a': 3, 'idx': 3},
     {'col_b': 8, 'idx': 3},
     {'col_a': 4, 'idx': 4},
     {'col_b': 9, 'idx': 4}]

df = pd.DataFrame(l)
df = df.set_index('idx')

我理解了这个内容

     col_a  col_b
idx              
0      0.0    NaN
0      NaN    5.0
1      1.0    NaN
1      NaN    6.0
2      2.0    NaN
2      NaN    7.0
3      3.0    NaN
3      NaN    8.0
4      4.0    NaN
4      NaN    9.0

但我想要这个

         col_a  col_b
    idx              
    0      0.0    5.0
    1      1.0    6.0
    2      2.0    7.0
    3      3.0    8.0
    4      4.0    9.0   

有什么想法吗?谢谢!

1
不是我当前情况下能做的事情 - 展示一个更实际的案例。 - RomanPerekhrest
使用您的示例,您可以执行 df[df['col_a'].notnull()].fillna(df[df['col_b'].notnull()]),但在实际情况下可能不起作用。 - Ben.T
你是否可能有一个组合 col_x;value(idx) 不止一次出现?如果是这样,代码应该返回什么? - Mr. T
4个回答

5
你可以按照 idx 进行分组并使用 .first() 方法获取第一项:
In [10]: df
Out[10]: 
   col_a  col_b  idx
0    0.0    NaN    0
1    NaN    5.0    0
2    1.0    NaN    1
3    NaN    6.0    1
4    2.0    NaN    2
5    NaN    7.0    2
6    3.0    NaN    3
7    NaN    8.0    3
8    4.0    NaN    4
9    NaN    9.0    4

In [11]: df.groupby("idx").first()
Out[11]: 
     col_a  col_b
idx              
0      0.0    5.0
1      1.0    6.0
2      2.0    7.0
3      3.0    8.0
4      4.0    9.0

或者调用 pivot_table

In [36]: df.pivot_table(index="idx")
Out[36]: 
     col_a  col_b
idx              
0      0.0    5.0
1      1.0    6.0
2      2.0    7.0
3      3.0    8.0
4      4.0    9.0

1
只需将级别为0的sum相加,即:
df.sum(level=0)

      col_a  col_b
idx              
0      0.0    5.0
1      1.0    6.0
2      2.0    7.0
3      3.0    8.0
4      4.0    9.0

0

DSM的答案对于您的示例完美地起作用,但在某些情况下可能会导致数据丢失,例如一个索引可能有多个col_a值的情况。可以使用这段更长的代码来解决这个问题。

import pandas

l = [{'col_a': 0, 'idx': 0},
     {'col_b': 5, 'idx': 0},
     {'col_a': 1, 'idx': 1},
     {'col_b': 6, 'idx': 1},
     {'col_a': 2, 'idx': 2},
     {'col_b': 7, 'idx': 2},
     {'col_a': 3, 'idx': 3},
     {'col_b': 8, 'idx': 3},
     {'col_a': 4, 'idx': 4},
     {'col_b': 9, 'idx': 4}]

# To flatten (unnest) a list with lists
flatten = lambda x: [item for sublist in x for item in sublist]

# Get all unique columns there (in case there are mote then two)
all_unique_cols = list(set(flatten([tuple(x.keys()) for x in l])))
all_unique_cols.remove('idx') # all except the index colname

df = pd.DataFrame()

# For all these columns we'll make a small df, and later join together
for i, col in enumerate(all_unique_cols):
    if i == 0:
        df = pd.DataFrame([x for x in l if col in x.keys()])
    else:
        df_tmp = pd.DataFrame([x for x in l if col in x.keys()])
        df = pd.merge(df, df_tmp, how='outer')

df.set_index('idx')

-1

这种方式分别初始化值和索引怎么样?

l = []
ix = []
for i in range(5):
    l.append({'col_a':i, 'col_b':i+5})
    ix.append(i)

df = pd.DataFrame(l, index=ix)

输出

 col_a  col_b
0   0   5
1   1   6
2   2   7
3   3   8
4   4   9

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接