'"ValueError: Length of values (2) does not match length of index (1)" when using pandas.insert
I am not sure why I am receiving the error message when all I am trying to do is to insert a list into a specific cell of pandas dataframe.
Here is the extractor function
def extractor():
.
.
.
df4 = df3.drop(dropped_columns, axis=1, errors='ignore')
df5 = df4.drop([1], axis=0, errors='ignore')
# I know that df3.iloc[0, 0] is always a string of characters or ''
df5.insert(0, "Sequence", stringSplitter4(df3.iloc[0, 0]))
.
.
.
This is the Utilities function used in extractor
def stringSplitter4(a_string: str) -> List:
"""This function splits a string in every other appearance of opening parantheses"""
return list(accumulate(findall('(?<![^)]).+?(?![^(])', a_string)))
And, here is the complete error message I am receiving:
Traceback (most recent call last):
File "c:/Users/username/Desktop/Project/my_script.py", line 91, in <module>
main()
File "c:/Users/username/Desktop/Project/my_script.py", line 71, in main
extractor(path, pep_id)
File "c:\Users\username\Desktop\Project\Utilities.py", line 253, in extractor
df5.insert(
File "C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\frame.py", line 4418, in insert
value = self._sanitize_column(value)
File "C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\frame.py", line 4509, in _sanitize_column
com.require_length_match(value, self.index)
File "C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\common.py", line 531, in require_length_match
raise ValueError(
ValueError: Length of values (2) does not match length of index (1)
Solution 1:[1]
As Jorge mentioned in his comment, I had to convert my list into a string first and then insert it into the cell. I would later, into the code, take care of the string by exploding it into a list in the right place of the code.
Instead of:
def stringSplitter4(a_string: str) -> List:
"""This function splits a string in every other appearance of opening parantheses"""
return list(accumulate(findall('(?<![^)]).+?(?![^(])', a_string)))
I did:
def stringSplitter4(a_string: str) -> List:
"""This function splits a string in every other appearance of opening parantheses"""
sequence_lst = list(accumulate(findall('(?<![^)]).+?(?![^(])', a_string)))
return '[' + ', '.join(sequence_lst) + ']'
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
