I have a bunch of series that I want to stack, make a dataframe, and add other series to that dataframe going through the same process.
I have done it step by step in jupyter notebook but when I try to make a for statement and a function to do what i can do (step-wise) in jupyter notebook the program fails giving me an error.
The code:
import pandas as pd
data = {'sum':[140.0, 45.0, 17907.0], 'mean':[35.00, 11.25, 4476.75],'count':[4, 4, 4]}
df = pd.DataFrame(data, index=['age', 'offspring', 'total_pop'])
data2 = {'sum':[14.0, 46.0, 14607.0], 'mean':[345.00, 121.25, 5476.75], 'count':[2, 2, 2]}
df2 = pd.DataFrame(data2, index=['age', 'offspring', 'total_pop'])
data3 = {'sum':[528.0, 15.0, 1407.0], 'mean':[700.00, 552.25, 4156.75], 'count':[3, 3, 3]}
df3 = pd.DataFrame(data3, index=['age', 'offspring', 'total_pop'])
def dosomething(df):
stacked = df.stack()
df = pd.Series(stacked)
df.to_frame()
dfd = pd.DataFrame(df)
df = df.join(dfd)
print(dfd)
total_df = [(df1), (df2), (df3,)]
for n in range(0, len(total_df)):
total_df[n] = dosomething(total_df[n])
Run Code Online (Sandbox Code Playgroud)
Expected:
1 2 3
age sum 140.00 14.00 528.00
mean 35.00 345.00 700.00
count 4.00 2.00 3.00
offspring sum 45.00 46.00 15.00
mean 11.25 121.25 552.25
count 4.00 2.00 3.00
total_pop sum 17907.00 14607.00 1407.00
mean 4476.75 5476.75 4156.75
count 4.00 2.00 3.00
Run Code Online (Sandbox Code Playgroud)
Actual error:
ValueError: columns overlap but no suffix specified: RangeIndex(start=0, stop=1, step=1)
尝试concat:
dfs = [df,df2, df3]
pd.concat([df.stack() for df in dfs], axis=1)
Run Code Online (Sandbox Code Playgroud)
输出:
0 1 2
age sum 140.00 14.00 528.00
mean 35.00 345.00 700.00
count 4.00 2.00 3.00
offspring sum 45.00 46.00 15.00
mean 11.25 121.25 552.25
count 4.00 2.00 3.00
total_pop sum 17907.00 14607.00 1407.00
mean 4476.75 5476.75 4156.75
count 4.00 2.00 3.00
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
69 次 |
| 最近记录: |