将列表追加到熊猫数据框的第一行和第一列

时间:2019-06-13 06:39:52

标签: python-3.x pandas dataframe append

我有一个4300 x 4300 pandas数据框(行和列),并想向第一行和第一列添加一个列表。我不知道怎么做,而不会用零完全填充数据框...

旧的4300 x 4300数据帧示例(摘录):

enter image description here

要添加的列表示例: [“轴”,“输出”,“组”,“多个”,“记录”]

新A x A数据帧的示例:

enter image description here

1 个答案:

答案 0 :(得分:2)

如果列表中的值不存在于索引和列中,请使用DataFrame.reindexIndex.appendIndex.union

L = ["axis","output","group","plurality","record"]
#if order is important
df = df.reindex(index=df.index.append(pd.Index(L)), columns= df.columns.append(pd.Index(L)))

#if index, columns values should be sorted
df = df.reindex(index=df.index.union(L), columns= df.columns.union(L))

如果索引,列和顺序中可能存在值,则很重要:

L1 = [x for x in L if x not in df.index]
L2 = [x for x in L if x not in df.columns]

df = df.reindex(index=df.index.append(pd.Index(L1)), columns= df.columns.append(pd.Index(L2)))
相关问题