As you can see in the picture, I want to convert the array to a list and finally to excel. But the problem I have is all the data on both sides have square brackets and quotations. what should I do to remove them? please help me to solve this problem, thank you!
To put it simply: My list is like [['a'], ['b'], ['c']] and I want to convert it to a,b,c
here is my code
def top_rank(result, md_adj, miRNAs, diseases):
row, col = result.shape
rows_list = []
for i in range(3):
pidx = np.argsort(-result[:, i])
sidx = np.argwhere(md_adj[:, i] == 1)
indices = np.argwhere(np.isin(pidx, sidx))
index = np.delete(pidx, indices)
a = diseases[i]
b = miRNAs[index]
c = np.vstack([a,b]).tolist()
rows_list.append(c)
df = pd.DataFrame(rows_list)
df = df.T
df.to_excel('test.xlsx')
CodePudding user response:
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