Suppose I have the following dataframe:
df = pd.DataFrame({"call 1": ['debit card','bond',np.nan],
"call 2": ['debit card','mortgage','spending limit'],
"call 3":['payment limit','debit card',np.nan]})
I want to add the name of columns to each cell as a dictionary such that I get: (EXPECTED OUTPUT)
pd.DataFrame({"call 1": [{'call 1':'debit card'},{'call 1':'bond'}, {'call 1': np.nan}],
"call 2": [{'call 2':'debit card'},{'call 2':'mortgage'},{'call 2':'spending limit'}],
"call 3":[{'call 3':'payment limit'},{'call 3':'debit card'},{'call 3':np.nan}]})
The method I used is turning everything to string, namely,
pd.DataFrame({col:str(col) ', ' for col in df}, index=df.index) df.astype(str)
which gives:
call 1 call 2 call 3
0 call 1, debit card call 2, debit card call 3, payment limit
1 call 1, bond call 2, mortgage call 3, debit card
2 call 1, nan call 2, spending limit call 3, nan
So I wonder how can I do this task such that I get a dict in each cell?
CodePudding user response:
Try this:
for col in df.columns:
df[col] = df[col].apply(lambda x: {col: x})