我正在尝试将两行插入到现有的数据框中,但似乎无法使其工作。现有的df为:
df1 = pd.DataFrame({"a" : [1,2,3,4,5,6], "block" : [1, 1, 2, 2, 3, 3]})我想在第一个和第二个块行之后添加两个空白行。我希望新的数据框看起来像这样:
df_new = pd.DataFrame({"a" : [1,2,0,3,4,0,5,6], "block" : [1, 1, 0, 2, 2, 0, 3, 3]})行中不需要有任何值,我计划将它们用作其他内容的占位符。我已经研究过添加行,但大多数帖子建议在数据框的开头或结尾添加一行,这在我的情况下行不通。
对我的困境有什么建议吗?
发布于 2016-04-05 08:19:59
import pandas as pd
# Adds a new row to a DataFrame
# oldDf - The DataFrame to which the row will be added
# index - The index where the row will be added
# rowData - The new data to be added to the row
# returns - A new DataFrame with the row added
def AddRow(oldDf, index, rowData):
newDf = oldDf.head(index)
newDf = newDf.append(pd.DataFrame(rowData))
newDf = newDf.append(oldDf.tail(-index))
# Clean up the row indexes so there aren't any doubles.
# Figured you may want this.
newDf = newDf.reset_index(drop=True)
return newDf
# Initial data
df1 = pd.DataFrame({"a" : [1,2,3,4,5,6], "block" : [1, 1, 2, 2, 3, 3]})
# Insert rows
blankRow = {"a": [0], "block": [0]}
df2 = AddRow(df1, 2, blankRow)
df2 = AddRow(df2, 5, blankRow)为了提高性能,您可以删除AddRow()函数中对Reset_Index()的引用,并在添加完所有行之后简单地调用它。
发布于 2016-04-05 08:47:10
如果您始终希望在block列中的每组值之后插入新的0行,则可以执行以下操作:
从你的数据框开始:
df1 = pd.DataFrame({"a" : [1,2,3,4,5,6], "block" : [1, 1, 2, 2, 3, 3]})使用block列中的值对其进行分组:
gr = df1.groupby('block')在每个组的末尾添加一行零:
df_new = gr.apply(lambda x: x.append({'a':0,'block':0}, ignore_index=True))重置新数据帧的索引:
df_new.reset_index(drop = True, inplace=True)发布于 2016-04-05 08:49:54
您可以简单地根据block列对数据执行groupby操作,然后对每个组底部的占位符执行concat操作,然后将其append到一个新的数据框架。
df1 = pd.DataFrame({"a" : [1,2,3,4,5,6], "block" : [1, 1, 2, 2, 3, 3]})
df1 # original data
Out[67]:
a block
0 1 1
1 2 1
2 3 2
3 4 2
4 5 3
5 6 3
df_group = df1.groupby('block')
df = pd.DataFrame({"a" : [], "block" : []}) # final data to be appended
for name,group in df_group:
group = pd.concat([group,pd.DataFrame({"a" : [0], "block" : [0]})])
df = df.append(group, ignore_index=True)
df
Out[71]:
a block
0 1 1
1 2 1
2 0 0
3 3 2
4 4 2
5 0 0
6 5 3
7 6 3
8 0 0https://stackoverflow.com/questions/36414561
复制相似问题