English 中文(简体)
如何消除
原标题:How to remove and empty string in a column in a dataframe?

我有一个数据框架,一个栏由清单价值组成。 我也以Excel格式和数据框架附上了情况。

column
"[
""Hello""
]"
"[
""Hello"", 
 ""Hi""
]"
"[
""Hello"", 
 ""Hi"",
 """"
]"
"[
"""",
""Hello"", 
 ""Hi""
]"
"[
""Hello"",
""""
]"
"[
"""",
""Hello""

]"

1][1]enter image description hereThe column value looks like

column
------
[
 "Hello" 
]
[
 "Hello", 
 "Hi"
]
[
 "Hello", 
 "Hi"
, 
 ""
]
[
 ""
, 
 "Hello", 
 "Hi"
]
[
 "Hello" 
, 
 ""
]
[
 ""
, 
 "Hello" 
]

So, I want to remove and "" from the list and have value as

column
------
["Hello"]
["Hello", "Hi"]
["Hello", "Hi"]
["Hello", "Hi"]
["Hello"]
["Hello"]

因此,我们如何利用安达和 p获得成果?

问题回答

我不敢确定如何处理你提供的投入数据,因为这种数据不正确格式。 然而,我认为,解决这一问题有两种办法。

Input data (as correct Python)

column = [
    [ 
 "Hello" 
 ],
    [ 
 "Hello" ,  
 "Hi"
 ],
    [ 
 "Hello" ,  
 "Hi"
 ,  
 ""
 ],
    [ 
 ""
 ,  
 "Hello" ,  
 "Hi"
 ],
    [ 
 "Hello" 
 ,  
 ""
 ],
    [ 
 ""
 ,  
 "Hello" 
 ]
]

Code: First map then List Comprehension

The map removes the whitespace including the newline characters. The list comprehension then removes the empty entries from each row ("").

def stripper(text):
    return text.strip().strip( " )

for row in column:
    output = list(map(stripper, row))
    print([i for i in output if i])

Output

[ Hello ]
[ Hello ,  Hi ]
[ Hello ,  Hi ]
[ Hello ,  Hi ]
[ Hello ]
[ Hello ]

请注意,最终结果有单一报价,而不是双重报价。 让我知道,这是否是你重新做的事。

For fun

就幸运而言,我从字面上完全拿到你的输入数据,并写了一套替换文件,确切地得出了你在该问题上的产出。

Input data

column = r"""[
 "Hello" 
]
[
 "Hello", 
 "Hi"
]
[
 "Hello", 
 "Hi"
, 
 ""
]
[
 ""
, 
 "Hello", 
 "Hi"
]
[
 "Hello" 
, 
 ""
]
[
 ""
, 
 "Hello" 
]""".splitlines()

Code

for row in column:
    print(row.replace( \n " ,  " ).replace( " \n ,  " ).replace( ""\n,  ,   ).replace( , ""\n ,   ).replace( "\n ,   ))

Output

["Hello"]
["Hello", "Hi]
["Hello", "Hi]
["Hello", "Hi]
["Hello"]
["Hello"]

举例来说,如果你提供了数据框架df,并附有栏目column,我们将使用以下代码。

def remove_empty_line(row):
    updated_list = list()
    for elem in row:
        updated_list.append(elem.replace("
", "").strip())
return updated_list

df["column"] = df["column"].apply(lambda row: remove_empty_line(row))

现在,你可以核对<代码>df.head(>。

如何做到这一点?

from ast import literal_eval

import pandas as pd


# Recreating data.
column = [
     [
 "Hello" 
] ,
     [
 "Hello", 
 "Hi"
] ,
     [
 "Hello", 
 "Hi"
, 
 ""
] ,
     [
 ""
, 
 "Hello", 
 "Hi"
] ,
     [
 "Hello" 
, 
 ""
] ,
     [
 ""
, 
 "Hello" 
] ,
]
df = pd.DataFrame({"column": column})

out = df.assign(
    # We map the following operations to "column".
    column=df.column
    .map(
        # Iterate over each value -- each will become a list of literals (in this case, strings).
        lambda x: [
            # We unpack the filtered values into the list.
            *filter(
                # Check the bool value of each item produced by `literal_eval`, keeping only those that are True.
                bool, literal_eval(x)
            )
        ]
    )
)
print(out)
        column
0      [Hello]
1  [Hello, Hi]
2  [Hello, Hi]
3  [Hello, Hi]
4      [Hello]
5      [Hello]




相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签