猿问

如何在python中将行字段更改为列标题?

我的数据格式如下


<table>

<tbody>

    <tr><th>A</th><th>B</th><th>C</th><th>D</th></tr>

    <tr><td>1</td><td>2</td><td>3</td><td>4</td></tr>

    <tr><td>2</td><td>1</td><td>3</td><td>2</td></tr>

    <tr><td>3</td><td>4</td><td>2</td><td>1</td></tr>

    <tr><td>4</td><td>2</td><td>1</td><td>3</td></tr>

</tbody>

</table>


我想将其转换为以下格式:


<table>

<tbody>

    <tr><th>1</th><th>2</th><th>3</th><th>4</th></tr>

    <tr><td>A</td><td>A</td><td>A</td><td>A</td></tr>

    <tr><td>B</td><td>B</td><td>C</td><td>B</td></tr>

    <tr><td>C</td><td>B</td><td>C</td><td>D</td></tr>

    <tr><td>D</td><td>C</td><td>D</td><td> </td></tr>

    <tr><td> </td><td>D</td><td> </td><td> </td></tr>

</tbody>

</table>

我曾尝试使用 Excel 数据透视表、Python 数据透视表,但无法获得所需的结果。

你能帮我吗?


catspeake
浏览 253回答 1
1回答

繁华开满天机

试试下面的代码。希望这会有所帮助:import pandas as pddf = pd.DataFrame({'A':[1,2,3,4],'B':[2,1,3,2],'C':[3,4,2,1],'D':[4,2,1,3]});data = {'A':[1,2,3,4],'B':[2,1,3,2],'C':[3,4,2,1],'D':[4,2,1,3]}将数据转换为所需的格式..new_data = dict()for key, value in data.items():&nbsp; &nbsp; for data1 in value:&nbsp; &nbsp; &nbsp; &nbsp; if data1 in new_data.keys():&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if key in new_data[data1]:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; pass&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; new_data[data1].append(key)&nbsp; &nbsp; &nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; new_data[data1]=[key]如果每个键的值长度不同,则熊猫将不会为传递的字典创建数据框。因此在这种情况下将值长度转换为与 4 相同。for key ,value in new_data.items():&nbsp; &nbsp; dif =&nbsp; 4 - len(value)&nbsp; &nbsp; new_data[key] = value + [None]*dif数据的输出将是:new_data{1: ['A', 'B', 'C', 'D'],&nbsp;2: ['A', 'B', 'C', 'D'],&nbsp;3: ['A', 'B', 'C', 'D'],&nbsp;4: ['A', 'C', 'D', None]}现在将其转换为数据框:&nbsp; &nbsp; 1&nbsp; &nbsp;2&nbsp; &nbsp;3&nbsp; &nbsp;40&nbsp; &nbsp;A&nbsp; &nbsp;A&nbsp; &nbsp;A&nbsp; &nbsp;A1&nbsp; &nbsp;B&nbsp; &nbsp;B&nbsp; &nbsp;B&nbsp; &nbsp;C2&nbsp; &nbsp;C&nbsp; &nbsp;C&nbsp; &nbsp;C&nbsp; &nbsp;D3&nbsp; &nbsp;D&nbsp; &nbsp;D&nbsp; &nbsp;D&nbsp; &nbsp;None
随时随地看视频慕课网APP

相关分类

Python
我要回答