擅长:python、mysql、java
<p>使用:</p>
<pre><code>L = ['ABC','GHI']
df1 = df.pivot('ID', 'var_name', 'var_value').fillna('')[L].reset_index()
print (df1)
var_name ID ABC GHI
0 1 This is abc1
1 2 This is abc2 This is ghi2
2 3 This is abc3
3 4 This is abc4
L1 = [df1.columns.tolist()] + df1.values.tolist()
print (L1)
[['ID', 'ABC', 'GHI'],
[1, 'This is abc1', ''],
[2, 'This is abc2', 'This is ghi2'],
[3, 'This is abc3', ''],
[4, 'This is abc4', '']]
</code></pre>
<p><strong>说明</strong>:</p>
<ol>
<li>首先<a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.pivot.html" rel="nofollow noreferrer">^{<cd1>}</a>,将<code>NaN</code>s替换为<a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.fillna.html" rel="nofollow noreferrer">^{<cd3>}</a>,转换用于筛选列的子集,并通过<a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reset_index.html" rel="nofollow noreferrer">^{<cd4>}</a>从索引创建列</li>
<li>上次创建嵌套列表和最后插入列名称</li>
</ol>
<p>编辑:</p>
<p>我尝试更改列表中值的顺序:</p>
^{pr2}$