muo*_*uon 2 python data-manipulation pandas
如何从这个表单中获取数据(数据的长表示):
import pandas as pd
df = pd.DataFrame({
'c0': ['A','A','B'],
'c1': ['b','c','d'],
'c2': [1, 3,4]})
print(df)
Run Code Online (Sandbox Code Playgroud)
日期:
c0 c1 c2
0 A b 1
2 A c 3
3 B d 4
Run Code Online (Sandbox Code Playgroud)
这种形式:
c0 c1 c2
0 A b 1
2 A c 3
3 A d NaN
4 B b NaN
5 B c NaN
6 B d 4
Run Code Online (Sandbox Code Playgroud)
长期从长到长的转型是这样做的唯一方法吗?
方法1
unstack
和stack
df.set_index(['c0', 'c1']).unstack().stack(dropna=False).reset_index()
Run Code Online (Sandbox Code Playgroud)
方法2
reindex
与产品
df.set_index(['c0', 'c1']).reindex(
pd.MultiIndex.from_product([df.c0.unique(), df.c1.unique()], names=['c0', 'c1'])
).reset_index()
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
123 次 |
最近记录: |