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

标签 python pandas dataframe data-science

在使用 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 before
print(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 = 5

for row in range(startRow):
    df.drop(row, inplace=True)
df = df.reset_index(drop=True)
header = list(df)
print(header)
print('')
print(df)

最佳答案

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

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

关于python - Pandas - 删除行后标题不会改变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62961859/

相关文章:

python - 使用 Numpy 在元组列表之间进行外部减法

Python Pandas 读取带有特定行终止符的 CSV 文件

python - 将 pandas 数据帧写入 HDF5

python - 使用 Pandas 对调查数据进行扁平化

r - 如果 R 数据框中的列包含特定文本,则删除重复的观察值

R - 使用组合从宽格式到长格式

python - 在 Python 中换行

python - 将 base64 字符串转换为与 OpenCV 兼容的图像

python - 读取数据时pygrib GRIB2段错误

python - 在python中查找三列的最大值和最小值