调整熊猫数据框中的列表长度

时间:2020-08-28 14:17:38

标签: python pandas

我有一个从列表列表中创建的dataframe

            A               B
0  ['a', 'b', 'c']      ['x', 'y']
1  ['e', 'f', 'g', 'h'] ['q', 'r']
...

,我想通过在'B'列表末尾添加元素来调整'A'列中列表的长度,以匹配'B'列中的列表。我该怎么办?

1 个答案:

答案 0 :(得分:0)

这是我对熊猫的做法:

# Load data
data = {'A': {0: "['a', 'b', 'c']", 
              1: "['e', 'f', 'g', 'h']"},
        'B': {0: "['x', 'y']", 
              1: "['q', 'r']"}}

df = pd.DataFrame(data)
df['A'] = df['A'].apply(lambda x: eval(x))
df['B'] = df['B'].apply(lambda x: eval(x))

# Def list update function
def list_adjust(l1, l2):
    if len(l1) > len(l2):
        return l2 + ['' for e in range(len(l1) - len(l2))]
    return l2

df['B'] = df.apply(lambda x: list_adjust(x['A'], x['B']), axis=1)

#Output
df
    A   B
0   [a, b, c]   [x, y, ]
1   [e, f, g, h]    [q, r, , ]