简体   繁体   中英

adjusting list lenghts in pandas dataframe

I have a dataframe created from list of lists:

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

and i want to adjust the lenghts of lists in column 'B' to match those from column 'A' by adding elements at the ends of lists in 'B' . How can I do that?

here is how I would do it with Pandas:

# 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, , ]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM