如何转换在每一列的每一行中包含列表的数据框

时间:2019-02-07 15:05:43

标签: python pandas dataframe transform

我有以下dataframe,它是for循环的输出之一。

df = pd.DataFrame()

df['Score'] = [['0-0','1-1','2-2'],['0-0','1-1','2-2']]
df ['value'] =[[0.08,0.1,0.15],[0.07,0.12,0.06]]
df ['Team'] = ['A','B']

我想将每行列表的每个元素转换为一列的每个元素。 以下是预期的输出。

enter image description here

有人可以帮助我进行变革吗?

谢谢

Zep

4 个答案:

答案 0 :(得分:2)

使用np.concatenate

r

输出:

import pandas as pd 
import numpy as np 

x = [['0-0','1-1','2-2'],['0-0','1-1','2-2']]
y = [[0.08,0.1,0.15],[0.07,0.12,0.06]]
z = ['A','B']
df = pd.DataFrame()

df['Score'] = np.concatenate(x)
df ['value'] = np.concatenate(y)
df['Team'] = np.repeat(z, len(df)/len(z))
print(df)

答案 1 :(得分:1)

您首先需要压平ist,可以使用itertools.chain

from itertools import chain
score = list(chain(*[['0-0','1-1','2-2'],['0-0','1-1','2-2']]))
value = list(chain(*[[0.08,0.1,0.15],[0.07,0.12,0.06]]))

pd.DataFrame({'score':score, 'value':value})

Score  value
0   0-0   0.08
1   1-1   0.10
2   2-2   0.15
3   0-0   0.07
4   1-1   0.12
5   2-2   0.06

答案 2 :(得分:1)

您可以使用chain.from_iterable来使输入变平:

from itertools import chain

import pandas as pd

data = [['0-0','1-1','2-2'],['0-0','1-1','2-2']]
values = [[0.08,0.1,0.15],[0.07,0.12,0.06]]

df = pd.DataFrame(data=list(zip(chain.from_iterable(data), chain.from_iterable(values))), columns=['score', 'value'])
print(df)

输出

  score  value
0   0-0   0.08
1   1-1   0.10
2   2-2   0.15
3   0-0   0.07
4   1-1   0.12
5   2-2   0.06

您也可以使用np.ravel

import numpy as np
import pandas as pd

data = [['0-0', '1-1', '2-2'], ['0-0', '1-1', '2-2']]
values = [[0.08, 0.1, 0.15], [0.07, 0.12, 0.06]]

df = pd.DataFrame({'score': np.array(data).ravel(), 'value': np.array(values).ravel()})
print(df)

答案 3 :(得分:1)

在每个数据帧列表上应用pd.Series后,您可以尝试一次取消索引堆积

df = pd.DataFrame()

df['Score'] = [['0-0','1-1','2-2'],['0-0','1-1','2-2']]
df ['value'] =[[0.08,0.1,0.15],[0.07,0.12,0.06]]    

df.stack().apply(pd.Series).ffill(1).unstack(level=0).T.reset_index(drop=True)

出局:

    Score   value   Team
0   0-0     0.08    A
1   0-0     0.07    B
2   1-1     0.1     A
3   1-1     0.12    B
4   2-2     0.15    A
5   2-2     0.06    B