Hello_world!
I have a DataFrame like this:
from pandas import DataFrame
df = DataFrame({"A": ['sd', 'df', 'gh', 'rv'],
"B": ['hj', '4r', 'tg', '2s'],
"C": ['hf', 'qw', 'e4', '7u'],
"D": ['1q', 'nc', 'xf', '7y'],
"E": ['9i', 'g7', 'ce', 'x3']})
or
A B C D E
0 sd hj hf 1q 9i
1 df 4r qw nc g7
2 gh tg e4 xf ce
3 rv 2s 7u 7y x3
I need to create a new column that will contain values of the set type, consisting of the values of the first five columns.
Expected result is:
A B C D E F
0 sd hj hf 1q 9i {'sd','hj', 'hf', '1q', '9i'}
1 df 4r qw nc g7 {'df','4r', 'qw', 'nc', 'g7'}
2 gh tg e4 xf ce {'gh','tg', 'e4', 'xf', 'ce'}
3 rv 2s 7u 7y x3 {'rv','2s', '7u', '7y', 'x3'}
print(type(df.loc[0, 'F'])) # <class 'set'>
print(type(df.loc[0, 'A'])) # <class 'str'>
My code:
from pandas import DataFrame
df = DataFrame({"A": ['sd', 'df', 'gh', 'rv'],
"B": ['hj', '4r', 'tg', '2s'],
"C": ['hf', 'qw', 'e4', '7u'],
"D": ['1q', 'nc', 'xf', '7y'],
"E": ['9i', 'g7', 'ce', 'x3']})
f = {df.loc[0, 'A'], df.loc[0, 'B'], df.loc[0, 'C'], df.loc[0, 'D'], df.loc[0, 'E']}
df = df.assign(F = f)
print(df)
...have ValueError: Length of values (5) does not match length of index (4).
If I rewrite the code so that the length of the values matches the length of the index:
from pandas import DataFrame
df = DataFrame({"A": ['sd', 'df', 'gh', 'rv'],
"B": ['hj', '4r', 'tg', '2s'],
"C": ['hf', 'qw', 'e4', '7u'],
"D": ['1q', 'nc', 'xf', '7y'],
"E": ['9i', 'g7', 'ce', 'x3']})
f = {df.loc[0, 'A'], df.loc[0, 'B'], df.loc[0, 'C'], df.loc[0, 'D']}
df = df.assign(F = f)
print(df)
...I have TypeError: 'set' type is unordered.
I ask the respected community for help to solve my problem.