如何用Python中的多年数据重塑dataframe

2024-10-03 21:30:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我相信我的问题可以通过一个循环来解决,但我还没有创造出这样的循环。我有一个像这样的数据样本 sample data

我希望有一个按年度组织的数据框架: result data

我尝试了pivot函数,创建了一个带有df['year']=数据框索引年份然后用pivot重新整形,但由于索引的原因,它将只填充第一年列。你知道吗

我已经设法做这种类型的重塑手动,但与数年的数据,这是耗时的解决方案。下面是手动解决方案的示例代码:

mydata = pd.DataFrame()
mydata2 = pd.DataFrame()
mydata3 = pd.DataFrame()
mydata1['1'] = df['data'].iloc[160:664]
mydata2['2'] = df['data'].iloc[2769:3273]
mydata3['3'] = df['data'].iloc[5583:6087]
mydata1.reset_index(drop=True, inplace=True)
mydata2.reset_index(drop=True, inplace=True)
mydata3.reset_index(drop=True, inplace=True)
mydata = pd.concat([mydata1, mydata2, mydata3],axis=1, ignore_index=True)
mydata.columns = ['78','88','00','05']

Tags: 数据truedataframedfdataindexdroppd
1条回答
网友
1楼 · 发布于 2024-10-03 21:30:18

欢迎来到StackOverflow!我想我从你的问题中理解了你的要求,但如果我错了,请纠正我。基本上,您希望使用一个轴心来重塑当前的pandas.DataFrame。我建立了一个示例数据集,并通过以下方式解决了问题:

import pandas as pd

#test set
df = pd.DataFrame({'Index':['2.1.2000','3.1.2000','3.1.2001','4.1.2001','3.1.2002','4.1.2002'],
                   'Value':[100,101,110,111,105,104]})

#create a year column for yourself
#by splitting on '.' and selecting year element.
df['Year'] = df['Index'].str.split('.', expand=True)[2]

#pivot your table
pivot = pd.pivot_table(df, index=df.index, columns='Year', values='Value')

#now, in my pivoted test set there should be unwanted null values showing up so
#we can apply another function that drops null values in each column without losing values in other columns
pivot = pivot.apply(lambda x: pd.Series(x.dropna().values))

我这边的结果

| Year | 2000 | 2001 | 2002 |
|   |   |   |   |
| 0    | 100  | 110  | 105  |
| 1    | 101  | 111  | 104  |

希望这能解决你的问题!你知道吗

相关问题 更多 >