How do I divide elements in a single column of a python dataframe?

孤街醉人 提交于 2021-02-17 03:01:52

问题


I need to divide every element in a specific column in a Pandas DataFrame by 100.

By default, the .div() function in Pandas divides all elements across all columns, and attempting to specify columns to divide leaves me with only those columns.

d = {
    'SYMBOL':['AAAAA','BBBBB','CCCCC'],
    'ASSETS':[5, 21, 74]}

data = pd.DataFrame(d,columns=['SYMBOL','ASSETS'])

data = data['ASSETS'].div(100)

So, starting with

    0     AAAAA 5
    1     BBBBB 21
    2     CCCCC 74

I end up getting

    0     0.05
    1     0.21
    2     0.74

When I want

    0     AAAAA 0.05
    1     BBBBB 0.21
    2     CCCCC 0.74

回答1:


data['ASSETS'] = data['ASSETS'].div(100)

You are overwriting your entire dataframe by assigning it back to data




回答2:


You can move symbols into the index of the dataframe, with set_index then, divide, and lastly reset_index:

d = {
    'SYMBOL':['AAAAA','BBBBB','CCCCC'],
    'ASSETS':[5, 21, 74]}

data = pd.DataFrame(d,columns=['SYMBOL','ASSETS'])

data = data.set_index('SYMBOL')

data = data.div(100)

print(data.reset_index())

Output:

  SYMBOL  ASSETS
0  AAAAA    0.05
1  BBBBB    0.21
2  CCCCC    0.74


来源:https://stackoverflow.com/questions/56858257/how-do-i-divide-elements-in-a-single-column-of-a-python-dataframe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!