How to remove square brackets from list in Python?
You could convert it to a string instead of printing the list directly:
print(", ".join(LIST))
If the elements in the list aren't strings, you can convert them to string using either repr
(if you want quotes around strings) or str
(if you don't), like so:
LIST = [1, "foo", 3.5, { "hello": "bye" }]
print( ", ".join( repr(e) for e in LIST ) )
Which gives the output:
1, 'foo', 3.5, {'hello': 'bye'}
Remove square brackets from lists in a column
IIUC, try this for string storage or list storge:
# String object
df_string = pd.DataFrame({'Fruits':['[apple, kiwi, pineapple, mango]',
'[strawberry, cherry, kiwi, orange]']})
df_string['Fruits'].str.replace('\[|\]','', regex=True)
Output:
0 apple, kiwi, pineapple, mango
1 strawberry, cherry, kiwi, orange
Name: Fruits, dtype: object
Or,
#List object
df_list = pd.DataFrame({'Fruits':[['apple', 'kiwi', 'pineapple', 'mango'],
['strawberry', 'cherry', 'kiwi', 'orange']]})
df_list['Fruits'].agg(', '.join)
Output:
0 apple, kiwi, pineapple, mango
1 strawberry, cherry, kiwi, orange
Name: Fruits, dtype: object
Note: df_list and df_string string representation looks identical.
print(df_list)
Fruits
0 [apple, kiwi, pineapple, mango]
1 [strawberry, cherry, kiwi, orange]
print(df_string)
Fruits
0 [apple, kiwi, pineapple, mango]
1 [strawberry, cherry, kiwi, orange]
how to remove square brackets and quotation mark when convert array to list in python
If you have nested lists [['a'], ['b'], ['c']]
then you can use for
-loop to make it flatten ['a', 'b', 'c']
data = [ ['a'], ['b'], ['c']]
flatten = [row[0] for row in data]
print(flatten)
Or you can also use fact that ["a"] + ["b"]
gives ["a", "b"]
- so you can use sum()
with []
as starting value
data = [['a'], ['b'], ['c']]
flatten = sum(data, [])
print(flatten)
And if you have numpy.array
then you could simply use arr.flatten()
import numpy as np
data = [['a'], ['b'], ['c']]
arr = np.array(data)
flatten = arr.flatten()
print(flatten)
BUT ... images show that you have [['X', 'Y'], ['a'], ['b'], ['c']]
and first element has two values - and this need different method to create flatten ['X Y', 'a', 'b', 'c']
. It needs to use for
-loop with join()
data = [['X', 'Y'], ['a'], ['b'], ['c']]
flatten = [' '.join(row) for row in data]
print(flatten)
The same using map()
data = [['X', 'Y'], ['a'], ['b'], ['c']]
flatten = list(map(",".join, data))
print(flatten)
And when you have flatten list then your code+
rows_list = [flatten]
df = pd.DataFrame(rows_list)
df = df.T
print(df)
gives
0
0 X Y
1 a
2 b
3 c
without []
and ''
BTW:
If you would creat dictionary rows_list[a] = b
(after converting a
to string and b
to flatten list) then you wouldn't need to transpose df = df.T
import pandas as pd
a = [['X', 'Y']]
b = [['a'], ['b'], ['c']]
print('a:', a)
print('b:', b)
print('---')
a = " ".join(sum(a, []))
b = sum(b, [])
print('a:', a)
print('b:', b)
print('---')
rows = dict()
rows[a] = b
df = pd.DataFrame(rows)
print(df)
gives
a: [['X', 'Y']]
b: [['a'], ['b'], ['c']]
---
a: X Y
b: ['a', 'b', 'c']
---
X Y
0 a
1 b
2 c
Remove Square Bracket and Breakdown List elements
Two good ways:
out = list(x for y in lst for x in y)
...or...
out = sum(lst,[])
how to remove the square bracket that are leftover in list with python?
You can try this below :
a = [[[1, 3, 2, 4], [1, 3, 2, 6]],
[[2, 4], [2, 6]],
[[3, 2, 4], [3, 2, 6]],
[[4]],
[[5, 4]],
[[6]]]
output = [elem for output_list in a for elem in output_list]
print(output)
Remove square brackets from a list of characters
[x for x in a if x not in "[]"]
Related Topics
How to Remove Strings Present in a List from a Column in Pandas
How to Use Variables in SQL Statement in Python
How to Get Maximum Length of Each Column in the Data Frame Using Pandas Python
How to Calculate Average a Dictionary from List of Dictionary Data
Making a Dictionary from Each Line in a File
How to Save a Pandas Dataframe Table as a Png
How to Remove \N from a List Element
How to Print Float to N Decimal Places Including Trailing 0S
Keep Other Columns When Doing Groupby
How to Sort a Single String Output in Ascii Descending Order Through a Function
Pandas - Find Rows With Matching Values in Two Columns and Multiply Value in Another Column
How to Plot Pandas Dataframe With Date (Year/Month)
Delete Rows Containing Numeric Values in Strings from Pandas Dataframe
How to Run Linux Terminal Command in Python in New Terminal
Webdriverexception: Message: Unknown Error: Chrome Failed to Start: Crashed
How to Sum Dictionaries Values With Same Key Inside a List
Sqlalchemy: How to Join Several Tables by One Query
Efficient Way to Unnest (Explode) Multiple List Columns in a Pandas Dataframe