【问题标题】:Why is this function not being applied to a pandas DataFrame?为什么这个函数没有应用于 pandas DataFrame?
【发布时间】:2021-05-21 12:44:01
【问题描述】:

我正在使用一个非常大的 Pandas DataFrame,并希望对每行在与每个属性对应的列中拥有的“属性”进行一次热编码。属性列在“属性”列中,我想对其进行迭代,然后定位各个列。最后,每一行应该有 1 代表它们拥有的属性,而 0 代表它们没有的属性。 使用较小的 DataFrame,此功能有效:

for i in range(len(df)):
    attributes = df.loc[i, 'attributes'].split(',')
    for item in attributes:
        df.loc[i, item] = 1

现在我正在处理更大的数据集,我的 Jupyter Notebook 的内核死了/当我尝试这个时它需要很长时间。我试图实现一个 apply() 方法,但是当我再次检查数据帧时,内核再次死掉,或者它似乎正在进行的更改(添加“1s”)不会持续存在。我将在下面列出我一直在尝试的选项,如果这里有问题,请告诉我,或者如果 Jupyter Notebook 不是处理大量数据的正确位置,我也非常感谢您对此提出建议。

尝试 1

def encode_ones(row):
    attr = row.attributes.split(',')
    row.loc[attr] = 1

df.apply(lambda row: encode_ones(row), axis=1)

尝试 2

def make_one(cell): 
    if cell == 0:
        return 1

df.apply(lambda row: make_one(row.loc[row.attributes]), axis=1)

尝试 3

def change_to_one(row):
    row.loc[[row.attributes]] = 1

df.apply(change_to_one, axis=1)

我知道在 Pandas 中对视图/副本和链式操作的混淆很常见,这就是我使用 .loc 的原因,但我在这里是否偏离了标准?

【问题讨论】:

    标签: python pandas dataframe jupyter-notebook one-hot-encoding


    【解决方案1】:

    我正在使用一个非常大的 Pandas DataFrame,并希望对每行在与每个属性对应的列中拥有的“属性”进行一次热编码。

    尝试在attributes 列上使用str.get_dummies 方法,看看它是否在大型数据集上表现更好。

    link to pandas documentation

    import pandas as pd
    
    df = pd.DataFrame({'attributes': ['a, b, c', 'a, c']})
    one_hot = df['attributes'].str.get_dummies(sep=', ')
    
    # Add one-hot encoding columns to the original data frame
    df = df.join(one_hot)
    

    这是生成的数据框。

      attributes  a  b  c
    0    a, b, c  1  1  1
    1       a, c  1  0  1
    

    看起来您的函数encode_ones 应该可以工作。您是否看到内存不足错误?

    【讨论】:

    • 谢谢蒂莫西!我现在正在尝试这个。至于encode ones,我一直在 df 的一个较小子集上尝试它以快速测试它,并且没有错误——当我再次检查 df 时没有什么不同。我想我只是收到“内核已死”错误,虽然我认为这是一个问题,但它并没有明确表示内存不足。
    • 在尝试您的方法大约半小时后,我收到消息“内核似乎已经死机。它将自动重新启动。”
    猜你喜欢
    • 2017-04-04
    • 2013-04-05
    • 2012-09-26
    • 2019-04-10
    • 2011-01-06
    • 2013-03-25
    • 1970-01-01
    • 2019-12-02
    • 2019-06-28
    相关资源
    最近更新 更多