[英]how do i convert a pandas dataframe from wide to long while keeping the index?
[英]How do I go from long to wide in this dataframe in pandas?
我有一個數據框,如下所示。
table some_date count
A_table 1/1/2020 451663386
1/10/2020 731919336
1/11/2020 95637849
1/12/2020 889510610
1/13/2020 834557529
1/14/2020 881597773
1/15/2020 838596734
1/16/2020 920376244
1/17/2020 832792096
1/18/2020 779652777
1/19/2020 834532103
1/2/2020 521978525
1/20/2020 777782936
...
B_table 2/24/2020 5492546
2/25/2020 5594754
2/26/2020 5201614
2/27/2020 5961111
2/28/2020 6811793
2/29/2020 6275315
2/3/2020 13307059
2/4/2020 11695493
2/5/2020 9034222
我想從上面到這個。
some_date A_table B_table
1/10/2020 731919336 NA
1/11/2020 95637849 NA
1/12/2020 889510610 NA
1/13/2020 834557529 NA
1/14/2020 881597773 5594754
1/15/2020 838596734 5201614
1/16/2020 920376244 5961111
1/17/2020 832792096 6811793
1/18/2020 779652777 6275315
1/19/2020 834532103 13307059
1/2/2020 521978525 11695493
1/20/2020 777782936 9034222
我試圖做一個支點
df.set_index('some_date').unstack('table')
這似乎不是正確的方法。 任何幫助表示贊賞。
謝謝
這取決於什么是df.index
。
如果table
是index
級別,則使用:
df1 = df.set_index('some_date', append=True)['count'].unstack(0)
如果table
和some_date
是some_date
的級別, MultiIndex
使用:
df1 = df['count'].unstack(0)
如果table
和some_date
是列,則使用:
df['some_date'] = df['some_date'].mask(df['some_date'] == '', np.nan).ffill()
df1 = df.pivot('some_date','table','count')
您可以使用 Pandas 數據框來合並 2 個表。 在此處查看文檔。 如果要保留兩個表中的所有條目,則需要使用“外部”聯接。
pd.merge(A_table, B_table, how='outer', on=some_date)
下面更詳細的語法(從上面的鏈接復制)
pd.merge(left, right, how='inner', on=None, left_on=None, right_on=None,
left_index=False, right_index=False, sort=True,
suffixes=('_x', '_y'), copy=True, indicator=False,
validate=None)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.