I have a csv file and I read it into array, the original csv a 5-row, 8-column file with empty elements
1 2 3 4 5 6 7 8
Row 1: '1 1' '4 4' '2 2'
Row 2: '3' '3' '3'
Row 3: '1 1 1 1' '1 1 1 1' '2 2 2 2'
Row 4: '2' '4' '2'
Row 5: '4' '4' '4'
I read it into my code:
[[nan '1 1' '4 4' nan nan nan '2 2' nan]
[nan '3' '3' nan nan nan '3' nan]
[nan '1 1 1 1' '1 1 1 1' nan nan nan '2 2 2 2' nan]
[nan '2' '4' nan nan nan '2' nan]
[nan '4' '4' nan nan nan nan '4']]
So what I want to get is to replace all empty elements into same number of -1
with other elements:
[['-1 -1' '1 1' '4 4' '-1 -1' '-1 -1' '-1 -1' '2 2' '-1 -1']
['-1' '3' '3' '-1' '-1' '-1' '3' '-1']
['-1 -1 -1 -1' '1 1 1 1' '1 1 1 1' '-1 -1 -1 -1' '-1 -1 -1 -1' '-1 -1 -1 -1' '2 2 2 2' '-1 -1 -1 -1']
['-1' '2' '4' '-1' '-1' '-1' '2' '-1']
['-1' '4' '4' '-1' '-1' '-1' '-1' '4']]
When I use re.match("\\d",element)
, I can not get the result. So could anyone help?
what about :
for line in csvdata:
multiplicity = max([len(datum.split(" ")) if isinstance(datum, str) else 0 for datum in line])
for datum in line:
if(not isinstance(datum, str)):
datum = " ".join(["-1"]*multiplicity)
It looks awful to me, but it should works.
try this:
xs=[["nan '1 1' '4 4' nan nan nan '2 2' nan"],
["nan '3' '3' nan nan nan '3' nan"],
["nan '1 1 1 1' '1 1 1 1' nan nan nan '2 2 2 2' nan"],
["nan '2' '4' nan nan nan '2' nan"],
["nan '4' '4' nan nan nan nan '4'"]]
for x in xs:
s = len(x[0].replace('nan','').replace(' ','').split("''")[0])-1
r = ' '.join('v'*s).replace('v', '-1')
r = "'%s'" % r
x[0] = x[0].replace('nan', r)
I believe you should make clear in your question you are using a library (numPy). Most of the solutions will work for Python, but as you are already using numpy, this is a better solution I believe
x = np.asarray(pd.read_csv("data/org8.csv"))
x[np.isnan(x)] = -1
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.