The size of the data in Python cells containing lists

I have a dataframe df:

        0               1               2   
Mon ['x','y','z']   ['a','b','c']   ['a','b','c']
Tue ['a','b','c']   ['a','b','c']   ['x','y','z']
Wed ['a','b','c']   ['a','b','c']   ['a','b','c']

The lists have different differences (maybe it also looks like), and I want to convert them to a form:

    0 1 2
Mon x a a
Mon y b b
Mon z c c
Tue a a x
Tue b b y
Tue c c z
Wed a a a
Wed b b b
Wed c c c

Referring to some previous SO questions, Expand lists of different lengths in Pandas , Split (explode) pandas write a data row in separate lines

I tried to use their solutions, but I can not get the desired result. How can I achieve this?

s1 = df[0]
s2 = df[1]
s3 = df[2]
i1 = np.arange(len(df)).repeat(s1.str.len())
i2 = np.arange(len(df)).repeat(s2.str.len())
i3 = np.arange(len(df)).repeat(s3.str.len())
df.iloc[i1, :-1].assign(**{'Shared Codes': np.concatenate(s1.values)})
df.iloc[i2, :-1].assign(**{'Shared Codes': np.concatenate(s2.values)})
df.iloc[i3, :-1].assign(**{'Shared Codes': np.concatenate(s3.values)})

Also, this is not a very reasonable way to do this if I have even more columns. Using python 2.7.

+4
source share
3 answers

This is one way to use itertools.chainand numpy.repeat:

import pandas as pd, numpy as np
from itertools import chain

df = pd.DataFrame({0: [['x', 'y', 'z'], ['a', 'b', 'c'], ['a', 'b', 'c']],
                   1: [['a', 'b', 'c'], ['a', 'b', 'c'], ['a', 'b', 'c']],
                   2: [['a', 'b', 'c'], ['x', 'y', 'z'], ['a', 'b', 'c']]},
                  index=['Mon', 'Tue', 'Wed'])

res = pd.DataFrame({k: list(chain.from_iterable(df[k])) for k in df},
                   index=np.repeat(df.index, list(map(len, df[0]))))

print(res)

#      0  1  2
# Mon  x  a  a
# Mon  y  b  b
# Mon  z  c  c
# Tue  a  a  x
# Tue  b  b  y
# Tue  c  c  z
# Wed  a  a  a
# Wed  b  b  b
# Wed  c  c  c
+2

, , : i.e:

ndf = pd.concat([df.apply(lambda x : [i[j] for i in x],1) for j in range(3)]).sort_index()

     0  1  2
Mon  x  a  a
Mon  y  b  b
Mon  z  c  c
Tue  a  a  x
Tue  b  b  y
Tue  c  c  z
Wed  a  a  a
Wed  b  b  b
Wed  c  c  c
+1

I would do it like this:

dfs = []
for day in df.index:
    part = pd.DataFrame(df.loc[day].tolist()).T
    part.index = np.repeat(day, len(df.columns))
    dfs.append(part)
result = pd.concat(dfs)
+1
source

Source: https://habr.com/ru/post/1696172/


All Articles