【问题标题】:Python 3 appending to a empty DataFramePython 3 附加到一个空的 DataFrame
【发布时间】:2015-05-12 09:28:18
【问题描述】:

对编码相当陌生。我已经查看了其他几个关于在 python 中附加 DataFrames 的类似问题,但无法解决问题。

我在 excel xls 文件中有以下数据 (CSV):

Venue Name,Cost ,Restriction,Capacity
Cinema,5,over 13,50
Bar,10,over 18,50
Restaurant,15,no restriction,25
Hotel,7,no restriction,100

我正在使用下面的代码尝试“过滤”出限制列下“无限制”的行。代码似乎一直工作到最后一行,即两个打印语句都给了我我所期望的。

import pandas as pd
import numpy as np

my_file = pd.ExcelFile("venue data.xlsx")
mydata = my_file.parse(0, index_col = None, na_values = ["NA"])

my_new_file = pd.DataFrame()

for index in mydata.index:
    if "no restriction" in mydata.Restriction[index]:
        print (mydata.Restriction[index])
        print (mydata.loc[index:index])
        my_new_file.append(mydata.loc[index:index], ignore_index = True)

【问题讨论】:

  • 问题仅仅是你认为append 就地行动吗?它没有,请参阅this。不过,这样想也不是没有道理,因为list.append 就是这样工作的。

标签: python-3.x pandas append


【解决方案1】:

不要循环遍历数据框。几乎从不需要。

用途:

df2 = df[df['Restriction'] != 'no restriction']

或者

df2 = df.query("Restriction != 'no restriction'")

【讨论】:

    猜你喜欢
    • 2013-05-11
    • 2021-10-17
    • 1970-01-01
    • 2019-05-21
    • 2021-04-09
    • 2021-09-08
    • 1970-01-01
    • 2016-05-31
    • 1970-01-01
    相关资源
    最近更新 更多