更改Pandas数据结构中元素的值 [英] Changing Values of elements in Pandas Datastructure
本文介绍了更改Pandas数据结构中元素的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经导入了.xls文件
和
I have imported .xls file with
ene2 = pd.read_excel('Energy Indicators.xls', index=False)
头看起来像这样
print(ene2.head())
Country Energy Supply Energy Supply per Capita % Renewable's
15 NaN Petajoules Gigajoules %
16 Afghanistan 321 10 78.6693
17 Albania 102 35 100
18 Algeria 1959 51 0.55101
19 American Samoa ... ... 0.641026
让我说我使用FOR循环交换了一些值
lets say that i used FOR loop to exchange some values
for value in ene2['Energy Supply']:
if value == 'Petajoules':
value = 'Gigajoules'
print(value)
在循环内s看起来不错
但是再次打印头,
print(ene2.head())
告诉我,尚未对DataStructure iteslf进行任何更改
show me that, no change has been applied to the DataStructure iteslf
和尾巴看起来与上面完全一样,但是我希望它会有所变化。
and tail looks exactly as above, but i expected it go got change.
推荐答案
而不是:
value = 'Gigajoules'
执行以下操作:
ene2.loc[ene2['Energy Supply'] == value, 'Energy Supply'] = 'Gigajoules'
通过使用 .loc
筛选正确的行和列,将其设置为相关的单元格。另一个答案是更简单的方法,但是我想让您了解,您并没有将更改仅通过value = blah回到数据框。
You have to set it to the relevant cell, by filtering for the correct rows and columns with .loc
. The other answer is the simpler method, but I wanted you to understand that you are not making the changes back to the dataframe with just value = blah.
这篇关于更改Pandas数据结构中元素的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文