Python 熊猫和种群:从日值(列)到月值(行)
我在重新格式化数据帧时遇到问题 我的输入是按符号列列出的日期值(每个符号的值具有不同的日期): 生成输入的代码Python 熊猫和种群:从日值(列)到月值(行),python,pandas,dataframe,python-datetime,Python,Pandas,Dataframe,Python Datetime,我在重新格式化数据帧时遇到问题 我的输入是按符号列列出的日期值(每个符号的值具有不同的日期): 生成输入的代码 data = [("01-01-2010", 15, 10), ("02-01-2010", 16, 11), ("03-01-2010", 16.5, 10.5)] labels = ["date", "AAPL", "AMZN"] df_input = pd.DataFrame.from_records(data, columns=labels) 所需输出为(每月行,每个月有新
data = [("01-01-2010", 15, 10), ("02-01-2010", 16, 11), ("03-01-2010", 16.5, 10.5)]
labels = ["date", "AAPL", "AMZN"]
df_input = pd.DataFrame.from_records(data, columns=labels)
所需输出为(每月行,每个月有新行):
生成输出的代码
data = [("01-01-2010","29-01-2010", "AAPL", 15, 20), ("01-01-2010","29-01-2010", "AMZN", 10, 15),("02-02-2010","30-02-2010", "AAPL", 20, 32)]
labels = ['bd start month', 'bd end month','stock', 'start_month_value', "end_month_value"]
df = pd.DataFrame.from_records(data, columns=labels)
含义(伪代码)
1.对于每一行,只取非nan值来创建一个新的“行”(可能是以日期为索引,[stock,value]为值的字典)。
2.只取当月业务开始或月末的行。
3.将这些行写入新的datatframe
我读过几篇文章,比如和更多。
所有这些都使用相同“类型”的数据帧进行处理,只需重新采样,而我需要更改为结构
到目前为止我的代码
# creating the new index with business days
df1 =pd.DataFrame(range(10000), index = pd.date_range(df.iloc[0].name, periods=10000, freq='D'))
from pandas.tseries.offsets import CustomBusinessMonthBegin
from pandas.tseries.holiday import USFederalHolidayCalendar
bmth_us = CustomBusinessMonthBegin(calendar=USFederalHolidayCalendar())
df2 = df1.resample(bmth_us).mean()
# creating the new index interseting my old one (daily) with the monthly index
new_index = df.index.intersection(df2.index)
# selecting only the rows I want
df = df.loc[new_index]
# creating a dict that will be my new dataset
new_dict = collections.OrderedDict()
# iterating over the rows and adding to dictionary
for index, row in df.iterrows():
# print index
date = df.loc[index].name
# values are the not none values
values = df.loc[index][~df.loc[index].isnull().values]
new_dict[date]=values
# from dict to list
data=[]
for key, values in new_dict.iteritems():
for i in range(0, len(values)):
date = key
stock_name = str(values.index[i])
stock_value = values.iloc[i]
row = (key, stock_name, stock_value)
data.append(row)
# from the list to df
labels = ['date','stock', 'value']
df = pd.DataFrame.from_records(data, columns=labels)
df.to_excel("migdal_format.xls")
一个大问题:
非常感谢 所以我找到了一种方法
name = stock_position.name
name = re.sub('[^a-zA-Z]+', '', name)
name = name[0:-4]
stock_position=stock_position.groupby([pd.TimeGrouper('M')]).agg(['first', 'last'])
stock_position["name"] = name
stock_position["return"] = ((stock_position["last"] / stock_position["first"]) - 1) * 100
stock_position.dropna(inplace=True)
df_migdal=df_migdal.append(stock_position)
df_migdal=df_migdal.round(decimals=2)
df_input.groupby([pd.TimeGrouper('M')]).agg(['first', 'last'])
你能添加吗?我的图片不好?不,因为无法复制数据,请检查我是否已使用此代码获取了月初和月底日期。。但我仍然不知道如何将这两个值放在同一列中,因为代码或数据示例永远都不好。您如何期望有人能从图片中复制您的代码?您能在控制台中运行图片以获取代码/数据吗?;)顺便说一句:我对获取股票数据感兴趣。你从哪里得到的数据?