Python 熊猫-标题不';删除行后不会更改
在使用Pandas删除几行数据帧后,头不会改变;它保持了行被删除前的状态 如何获取更新的标题Python 熊猫-标题不';删除行后不会更改,python,pandas,dataframe,data-science,Python,Pandas,Dataframe,Data Science,在使用Pandas删除几行数据帧后,头不会改变;它保持了行被删除前的状态 如何获取更新的标题 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
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 before
print(header)
print('')
print(df) # the DataFrame is ok, without the removed rows (as expected)
最简单的例子:
在pandas中,“header”是列的名称,与dataframe中的数据分开存储。根据您的评论,我认为您需要先更改列名,然后删除行
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
请显示您的数据帧示例。为什么要尝试以这种方式删除行,而不是使用索引来选择要保留的行?但是通过这样做:
header=list(df)
实际上是分配列名(或者至少在我的pandas
版本中是这样做的,因此它应该保持未被触及的dbtw而不是for
循环只需使用:df.drop(list(df.index)[:rowStart],inplace=True)
但标题是列名-在删除(在您的例子中涉及行)和重置索引之后,它应该保持完全相同。)(关注点索引)列标题不是数据框的第一行。它们是在创建数据框时确定的。如果您向我们显示示例数据,应该很容易有人帮助您。完美。它起了作用。我所做的唯一更改是为“df.columns”设置索引设置为0,因为我正在删除行并重置索引。谢谢!我对代码做了一些调整,这样您就不必更改df.columns.mazing的索引。我注意到在删除行之前设置列也很重要。否则,第一行(0)将重复或缺少/没有标题。
Job Revenue
0 abc123 1000
1 hey098 2000