为了账号安全,请及时绑定邮箱和手机立即绑定

Pandas - 删除行后标题不会改变

Pandas - 删除行后标题不会改变

婷婷同学_ 2023-03-16 16:10:16
使用 Pandas 删除 DataFrame 的几行后,标题不会改变;它保持行被删除之前的状态。我怎样才能得到更新的标题?for row in range(rowStart): # rowStart is my index (int). It means it should drop all rows up to this    df.drop(row, inplace=True)df = df.reset_index(drop=True)header = list(df) # even assigning the header after the drop, it keeps returning the same as beforeprint(header)print('')print(df) # the DataFrame is ok, without the removed rows (as expected)最小的例子:data = {    '': '',    'asd': '',    'bfdgfd': '',    'trytr': '',    'jlhj': '',    'Job': 'Revenue',    'abc123': 1000.00,    'hey098': 2000.00}df = pd.DataFrame(data.items(),    columns=['Unnamed: 0', 'Unnamed: 1'])header = list(df)print(header)print('')print(df)startRow = 5for row in range(startRow):    df.drop(row, inplace=True)df = df.reset_index(drop=True)header = list(df)print(header)print('')print(df)
查看完整描述

1 回答

?
ABOUTYOU

TA贡献1812条经验 获得超5个赞

在熊猫中,“标题”是列的名称,与数据框中的数据分开存储。根据您的意见,我认为您需要先更改列名,然后删除行。


import pandas as pd


data = {

    '': '',

    'asd': '',

    'bfdgfd': '',

    'trytr': '',

    'jlhj': '',

    'Job': 'Revenue',

    'abc123': 1000.00,

    'hey098': 2000.00

}

df = pd.DataFrame(data.items(),

    columns=['Unnamed: 0', 'Unnamed: 1'])

startRow = 5


df.columns = df.loc[startRow].to_list()  # set the "header" to the values in this row

df = df.loc[startRow+1:].reset_index(drop=True)  # select only the rows you want

在这段代码之后,df 将是:


      Job Revenue

0  abc123    1000

1  hey098    2000


查看完整回答
反对 回复 2023-03-16
  • 1 回答
  • 0 关注
  • 114 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信