【问题标题】:Python pandas empty df but columns has elementsPython pandas为空df但列有元素
【发布时间】:2019-12-09 12:32:25
【问题描述】:

我的脚本中确实有一些令人讨厌的东西,但不知道出了什么问题。当我尝试过滤我的数据框,然后将行添加到我想要导出到 excel 的新行时,就会发生这种情况。

文件导出为空 DF,打印也显示“报告”为空,但是当我尝试打印 report.Name、report.Value 等时,我得到了正常且正确的元素输出。另外我只能将一列导出到 excel 而不是整个 DF 看起来像空的.... 什么会导致这种奇怪的事故?

这是我的脚本:

df = pd.read_excel('testfile2.xlsx')
report = pd.DataFrame(columns=['Type','Name','Value'])

for index, row in df.iterrows():
    if type(row[0]) == str:
        type_name = row[0].split(" ")
        if type_name[0] == 'const':
            selected_index = index
            report['Type'].loc[index] = type_name[1]
            report['Name'].loc[index] = type_name[2]
            report['Value'].loc[index] = row[1]

        else:
            for elements in type_name:
                report['Value'].loc[selected_index] += " " + elements

    elif type(row[0]) == float:
        df = df.drop(index=index)

print(report) #output - Empty DataFrame
print(report.Name) output - over 500 elements

【问题讨论】:

标签: python pandas export-to-csv export-to-excel


【解决方案1】:

您正在尝试操纵导致所描述行为的不存在的系列。

用一个更简单的例子做你所做的事情,我得到了相同的结果:

report = pd.DataFrame(columns=['Type','Name','Value'])
report['Type'].loc[0] = "A"
report['Name'].loc[0] = "B"
report['Value'].loc[0] = "C"

print(report) #empty df
print(report.Name) # prints "B" in a series

简单的解决方案:只需添加整行而不是三个单个值:

report = pd.DataFrame(columns=['Type','Name','Value'])
report.loc[0] = ["A", "B", "C"]

或在您的代码中:

report.loc[index] = [type_name[1], type_name[2], row[1]]

如果您想以与现在相同的方式执行此操作,则首先需要将具有给定索引的空系列添加到 DataFrame 中,然后才能对其进行操作:

report.loc[index] = pd.Series([])
report['Type'].loc[index] = type_name[1]
report['Name'].loc[index] = type_name[2]
report['Value'].loc[index] = row[1]

【讨论】:

    猜你喜欢
    • 2015-09-02
    • 2020-12-29
    • 2020-09-04
    • 1970-01-01
    • 2019-07-26
    • 2021-05-06
    • 1970-01-01
    • 2021-10-22
    • 1970-01-01
    相关资源
    最近更新 更多