繁体   English   中英

如何在 python dataframe 中最后添加项目并删除第一项?

[英]How to add item last and remove first item in python dataframe?

我的dataframe是这样的:

data = {
  "a": [420, 380, 390],
  "b": [50, 40, 45]
}

df = pd.DataFrame(data)

我想在这个 dataframe 的末尾添加新项目,并删除第一个项目。 我的意思是每次添加 cont 将是 3。

新项目添加

{"a": 300, b: 88}

最后的情况将是:

data = {
  "a": [380, 390, 300],
  "b": [40, 45, 88]
}

有没有捷径可以做到这一点?

您可以使用pd.concat ,因为append已被弃用。 参考

dct = {"a": 300, "b": 88}
df_new = pd.concat([df, pd.Series(dct).to_frame().T]
                  ).iloc[1:, :].reset_index(drop=True)
print(df_new)

# If maybe the values of 'dict' have multiple items.
# dct = {"a": [300, 400], "b": [88, 98]}
# df_new = pd.concat([df, pd.DataFrame(dct)]
#                   ).iloc[1:, :].reset_index(drop=True)

您可以使用pandas.DataFrame.appenddf添加一个新行,然后删除index的第一行基数。 (如果有必要,最后使用reset_index

dct = {"a": 300, "b": 88}
df_new = df.append(dct, ignore_index=True).drop(0, axis=0).reset_index(drop=True)
print(df_new)

Output:

     a   b
0  380  40
1  390  45
2  300  88

使用concat

df = pd.concat([df.iloc[1:],
                pd.DataFrame.from_dict({0: d}, orient='index')], 
               ignore_index=True)

Output:

     a   b
0  380  40
1  390  45
2  300  88

您可以通过df.append()将 append 新行添加到现有的 dataframe 中。 在您的示例中,这将是

new_row = {"a": 300, "b": 88}
df2 = df.append(new_row, ignore_index=True)

(注意append同时适用于Dataframedict对象,但后者需要ignore_index=True

您可以通过以下方法之一从 dataframe 中删除第一行:

  1. Select 使用iloc
df3 = df2.iloc[1:, :]

这将对除第一行和所有列之外的所有行进行切片。

  1. 使用 drop 删除第一行。
df3 = df2.drop(df.index[0], axis=0, inplace=False)

或者您可以使用inplace=True修改df2 ,在这种情况下将返回None

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM