2017-08-25 126 views
1

新的熊貓和新的stackoverflow(真的),任何建議,非常感謝!熊貓dataframe:在列上執行計算

我有這樣的數據幀DF:

  col1  col2  col3 
Date           
2017-08-24 100  101  105 
2017-08-23 102  102  107 
2017-08-22 101  100  106 
2017-08-21 103  99  106 
2017-08-18 103  98  108 
... 

現在我想與每一列,例如的值執行一些計算計算每個值的對數。

我認爲這是一個好主意,循環的列和創建一個新的臨時數據框與結果列。 這個新的數據幀應該是這樣的。例如:

  col1  RN  LOG 
Date           
2017-08-24 100  1  2 
2017-08-23 102  2  2,008600 
2017-08-22 101  3  2,004321 
2017-08-21 103  4  2,012837 
2017-08-18 103  5  2,012837 

所以,我想這個for循環:

for column in df: 
    tmp_df = df[column] 
    tmp_df['RN'] = range(1, len(tmp_df) + 1) # to create a new column with the row number 
    tmp_df['LOG'] = np.log(df[column]) # to create a new column with the LOG 

然而,這並不打印旁邊COL1新列,但有以下其他。結果是這樣的:

Name: col1, Length: 86, dtype: object 
Date 
2017-08-24 00:00:00            100 
2017-08-23 00:00:00            102 
2017-08-22 00:00:00            101 
2017-08-21 00:00:00            103 
2017-08-18 00:00:00            103 
RN,"range(1, 86)" 
LOG,"Date 
2017-08-24 2 
2017-08-23 2,008600 
2017-08-22 2,004321 
2017-08-21 2,012837 
2017-08-18 2,012837 

00:00:00加入在第一部分的日期......

我也嘗試過一些與分配:

tmp_df = tmp_df.assign(LN=np.log(df[column])) 

但這結果爲「AttributeError:」'Series'object has no attribute'assign'「」

如果有人能指出我的方向是正確的,那真的很棒。 謝謝!

+0

你可以發佈你想要的輸出看起來像什麼嗎?我不清楚最終結果應該是什麼 – johnchase

+0

嗨,約翰,我正在爲每列創建一個新的數據表單,並且它應該包含原始列c1 - cN和它旁邊的計算值,例如,行號和c1的LOG。我試圖在第二個代碼片段中顯示它 – RazzleDazzle

回答

1

您的循環是一個好主意,但是你需要在新列創建熊貓系列是這樣的:

for column in df: 
    df['RN ' + column] = pd.Series(range(1, len(df[column]) + 1)) 
    df['Log ' + column] = pd.Series(np.log(df[column])) 
0

現在我想通了。 :)

import pandas as pd 
import numpy as np 
... 
for column in df: 
    tmp_res=pd.DataFrame(data=df[column]) 
    newcol=range(1, len(df) + 1) 
    tmp_res=tmp_res.assign(RN=newcol) 
    newcol2=np.log(df[column]) 
    tmp_res=tmp_res.assign(LN=newcol2) 

這將打印彼此相鄰的所有列:

  col1  RN  LOG 
Date           
2017-08-24 100  1  2 
2017-08-23 102  2  2.008600 
2017-08-22 101  3  2.004321 
2017-08-21 103  4  2.012837 
2017-08-18 103  5  2.012837 

現在我可以去處理它們或把它們都放在一個CSV/Excel文件。 感謝您的所有建議!