Convert Each Element Of Pandas Dataframe Into Dict
I am trying to add feature index to each element of pandas dataframe such that each element will be like column_number:feature_value. For example, if input is like this: co
Solution 1:
I used the following code to get my desired output format:
f_out = open('check_features.csv','w')
X = feature_matrix1.drop(['Disease'], axis=1)
Y = feature_matrix1['Disease'].tolist()
for i in tqdm(range(X.shape[0])):
line = ''
line += str(Y[i]) + '\t'for j inrange(X.shape[1]):
line += str(j+1) + ':' + str(X.iloc[i,j]) + '\t'
line += '\n'
f_out.write(line)
f_out.close()
Solution 2:
First convert to string and use radd
to get expect output:
>>>df.astype(str).radd([f'{i+1}:'for i inrange(len(df.columns))])
col1 col2
row1 1:1.23 2:2.24
row2 1:0.42 2:5.52
Solution 3:
You can use df.columns.get_loc()
to get the column integer location number (0-based) and then string concatenate with the column values for each column, as follows:
for col in df.columns:
df[col] = str(df.columns.get_loc(col) + 1) + ':' + df[col].astype(str)
Result:
print(df)
col1 col2
row1 1:1.23 2:2.24
row2 1:0.42 2:5.52
Solution 4:
It works
for c in df.columns:
df[c] = df[c].apply(lambda x:f"{c[-1]}:{x}")
result
col1 col2
row1 1:1.23 2:2.24
row2 1:0.42 2:5.52
Solution 5:
Short version In
[f"{i+1}:"for i inrange(df.shape[1])] + df.astype(str)
Out
col1 col2
row1 1:1.23 2:2.24
row2 1:0.42 2:5.52
Post a Comment for "Convert Each Element Of Pandas Dataframe Into Dict"