【问题标题】:Fill pandas data frame using .append()使用 .append() 填充熊猫数据框
【发布时间】:2016-01-19 01:00:36
【问题描述】:

我有一个数据框,其中有一列包含逗号分隔的字符串。我想要做的是用逗号分隔它们,计算它们并将计数的数字附加到一个新的数据框中。如果该列包含一个只有一个元素的列表,我想区分它是字符串还是整数。如果它是一个整数,我想将该行中的值 0 附加到新的 df 中。 我的代码如下所示:

def decide(dataframe):
    df=pd.DataFrame()

    for liste in DataFrameX['Column']:
        x=liste.split(',')
        if len(x) > 1:
            df.append(pd.Series([len(x)]), ignore_index=True)
        else:
            #check if element in list is int
            for i in x:
                try:
                    int(i)
                    print i
                    x = []

                    df.append(pd.Series([int(len(x))]), ignore_index=True)
                except:
                    print i
                    x = [1]
                    df.append(pd.Series([len(x)]), ignore_index=True)
    return df

输入数据如下所示:

   C1  
0  a,b,c
1  0
2  a
3  ab,x,j

如果我现在使用原始数据框作为输入运行该函数,它将返回一个空数据框。通过 try/except 语句中的 print 语句,我可以看到一切正常。问题是将结果值附加到新的数据框。我必须在我的代码中更改什么?如果可能,请不要给出完全不同的解决方案,而是告诉我我在代码中做错了什么,以便我学习。

******************更新****************************** ********

我编辑了代码,使其可以作为 lambda 函数调用。现在看起来是这样的:

def decide(x):
    For liste in DataFrameX['Column']:

        x=liste.split(',')
        if len(x) > 1:
            x = len(x)
            print x
        else:
            #check if element in list is int
            for i in x:
                try:
                    int(i)
                    x = []
                    x = len(x)
                    print x

                except: 
                    x = [1]
                    x = len(x)
                    print x

我这样称呼它:

df['Count']=df['C1'].apply(lambda x: decide(x))

它打印正确的值,但新列只包含None

有什么想法吗?

【问题讨论】:

  • 作为一般规则,dataframe 不使用 for 循环进行迭代,您应该使用类似 df.apply(lambda x: len(x)) 的东西,是您正在迭代的问题吗DataFrameX,但您将数据框传递给函数?你应该发布你的输入,并在你的 try/except 中提出错误以查看问题
  • 想到了,但不知道如何在 if + try except 语句中构建。不过我会试试的。
  • 您不需要使用 lambda,只需将您喜欢的任何函数传递给 apply
  • @karlson 你是对的,但我认为 lambda 对传递的内容更清楚
  • @user1883737 但是您不能在 lambdas 中使用 try-except 块,这就是 OP 可能想要使用普通函数的原因。

标签: python pandas append dataframe


【解决方案1】:

这是一个好的开始,可以简化,但我认为它可以按预期工作。

#I have a dataframe with a column containing comma separated strings.
df = pd.DataFrame({'data': ['apple, peach', 'banana, peach, peach, cherry','peach','0']})

# What I want to do is separate them by comma, count them and append the counted number to a new data frame.
df['data'] = df['data'].str.split(',')
df['count'] = df['data'].apply(lambda row: len(row))
# If the column contains a list with only one element
df['first'] = df['data'].apply(lambda row: row[0])
# I want to differentiate wheather it is a string or an integer
df['first'] = pd.to_numeric(df['first'], errors='coerce')
# if the element in x is an integer, len(x) should be set to zero 
df.loc[pd.notnull(df['first']), 'count'] = 0
# Dropping temp column
df.drop('first', 1, inplace=True)
df

                                data  count
0                    [apple,  peach]      2
1  [banana,  peach,  peach,  cherry]      4
2                            [peach]      1
3                                [0]      0

【讨论】:

  • 感谢您的回答。我的问题是,当整数 0 在计算的列表中时, len(row) 仍然会给我数据框中的数字 1,我想要 0。
  • 是只需要用列表中的整数替换零还是所有整数值?
  • 如果x中的元素是整数,len(x)应该设置为零
猜你喜欢
  • 2016-12-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-30
  • 1970-01-01
  • 2022-11-16
  • 2021-10-02
  • 2020-11-08
相关资源
最近更新 更多