我想从初始值-3.9找到Dew_P Temp (C)
的pct_change。我想在新专栏中使用pct_change。
来源:
weather = pd.read_csv('https://raw.githubusercontent.com/jvns/pandas-cookbook/master/data/weather_2012.csv')
weather[weather.columns[:4]].head()
Date/Time Temp (C) Dew_P Temp (C) Rel Hum (%)
0 2012-01-01 -1.8 -3.9 86
1 2012-01-01 -1.8 -3.7 87
2 2012-01-01 -1.8 -3.4 89
3 2012-01-01 -1.5 -3.2 88
4 2012-01-01 -1.5 -3.3 88
我尝试过这种for循环的变体(甚至可以添加这里显示的索引),但无济于事:
for index, dew_point in weather['Dew_P Temp (C)'].iteritems():
new = weather['Dew_P Temp (C)'][index]
old = weather['Dew_P Temp (C)'][0]
pct_diff = (new-old)/old*100
weather['pct_diff'] = pct_diff
我认为问题是weather['pct_diff']
,它不需要new
它取数据框的最后一个值并从old
中减去它
所以它总是(2.1-3.9)/3.9*100因此我的百分比变化总是-46%。
我想要的最终结果是:
Date/Time Temp (C) Dew_P Temp (C) Rel Hum (%) pct_diff
0 2012-01-01 -1.8 -3.9 86 0.00%
1 2012-01-01 -1.8 -3.7 87 5.12%
2 2012-01-01 -1.8 -3.4 89 12.82%
有什么想法吗?谢谢!
答案 0 :(得分:8)
您可以使用iat
来访问标量值(例如iat[0]
访问系列中的第一个值。)
df = weather
df['pct_diff'] = df['Dew_P Temp (C)'] / df['Dew_P Temp (C)'].iat[0] - 1
答案 1 :(得分:4)
IIUC你可以这样做:
In [88]: ((weather['Dew Point Temp (C)'] - weather.ix[0, 'Dew Point Temp (C)']).abs() / weather.ix[0, 'Dew Point Temp (C)']).abs() * 100
Out[88]:
0 0.000000
1 5.128205
2 12.820513
3 17.948718
4 15.384615
5 15.384615
6 20.512821
7 7.692308
8 7.692308
9 20.512821
答案 2 :(得分:2)