将Pandas中的行转换为列

rslzwgfq  于 2022-11-05  发布在  其他
关注(0)|答案(3)|浏览(166)

我正在使用Pandas将dict转换为html表,但无法弄清楚,如何在这种情况下将行转换为列?

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")

实际产量:

所需输出:

kg7wmglp

kg7wmglp1#

更改使用pd.DataFrame.from_dict创建df的方式

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()}

# orient here

df = pd.DataFrame.from_dict(c, orient='index')

df.to_html("tmp/a1.html")

输出

vh0rcniy

vh0rcniy2#

尝试旋转和转置

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)

输出功率

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
kfgdxczn

kfgdxczn3#

使用原始字典上的Series:

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

变体:
第一个

相关问题