Home > Blockchain >  Convert row to column in pandas
Convert row to column in pandas

Time:11-05

I am using pandas to convert dict to html table, but not able to figure out, how to convert row to column in this case?

import pandas as pd

c = {'result': 'FAIL', "LinkA": "https:// example.com/dwdewdbeuwwuvdwudwufdqwdqqdqdqdqwedeuq.txt",
     "NDT": "https://example.com/dgwuydweufdwuefgwfwfdwefef.txt",
     "KKT": "https:// example.com/fewnewvbbcuwecvwxvwwecewc.txt"}
c = {k:[v] for k,v in c.items()}
df = pd.DataFrame(c)
df.to_html("/tmp/a1.html")

Actual Output: Actual Output

Required Output:

Expected Output

CodePudding user response:

Change how you create the df using enter image description here

CodePudding user response:

try pivot and transpose

data="""result,fail
LinkA,1
NDT,2
KKT,3
LinkA,4
NDT,5
KKT,6
"""

df = pd.read_csv(StringIO(data), sep=",")
df.columns=columns=["result","fail"]
#print(df.T)
df = df.pivot(index="result", columns="fail", values="fail")
print(df.T)

output

result  KKT  LinkA  NDT
fail                   
1       NaN    1.0  NaN
2       NaN    NaN  2.0
3       3.0    NaN  NaN
4       NaN    4.0  NaN
5       NaN    NaN  5.0
6       6.0    NaN  NaN

CodePudding user response:

Use a Series on the original dictionary:

pd.Series(c).reset_index().to_html()

Variants:

pd.Series(c).reset_index(name='value').to_html()
pd.Series(c).reset_index().to_html(header=False, index=False)
  • Related