Home>

I'm a beginner and don't really understand how to use pandas.

         1
0 137580000
1 288
2 477708
3 1905000
4 447824


There is such a data frame, besides the second column (index (1))
Currency format
¥ 1,000,000
I want to set.

To make it happen

wb3.loc [0] = wb3.loc [0] .apply ('\ {:,}'. format)
wb3.loc [2] = wb3.loc [2] .apply ('\ {:,}'. format)
wb3.loc [3] = wb3.loc [3] .apply ('\ {:,}'. format)
wb3.loc [4] = wb3.loc [4] .apply ('\ {:,}'. format)


But this is too bad

for i in range (0,5):
    if i! = 1:
        wb3.loc [i] = wb3.loc [i] .apply ('\ {:,}'. format)


I did.
Using lamdba etc. as a method of Pandas
Format other than "Index! = 1"
I thought there should be a method like that, but this is not the correct answer! I can't grasp it.

I would like to know for later study, but could anyone please teach me?
Thank you.

What I tried ↓

## wb3 = wb3.apply (lambda x:'\ {:,}'. format, subset = pd.IndexSlice [wb3.index [wb3.index! = 1],:])
→ TypeError:<lambda>() got an unexpected keyword argument'subset'
## wb3 = wb3.applymap (lambda x:'\ {:,}'. format, subset = pd.IndexSlice [wb3.index [wb3.index! = 1],:])
→ TypeError: applymap () got an unexpected keyword argument'subset'
## wb3 = wb3.style.applymap (lambda x:'\ {:,}'. format, subset = pd.IndexSlice [wb3.index [wb3.index! = "1"],:])
→ Attribute Error:'Styler' object has no attribute'loc'
## wb3 = wb3.style.apply (lambda x: ['\ {:,}'. format if x.name in [0,2,3,4] else'{:,}'. format], axis = 1)
→ Attribute Error:'Styler' object has no attribute'loc'
  • Answer # 1

    You can apply the format by specifying the index by applying in the row direction as shown below.
    However, regarding the type of each column value, please note that the original numerical value and the character string to which the format has been applied are mixed.

    import pandas as pd
    wb3 = pd.DataFrame ({'1': [137580000,288,477708]})
    def f (row):
        if row.name! = 1:
            return'\ {:,}'. format (row ['1'])
        return row ['1']
    wb3 ['1'] = wb3.apply (f, axis = 1)
    print (wb3)
    # 1
    # 0 ¥ 137,580,000
    # 1 288
    # 2 ¥ 477,708
    print (wb3 ['1']. tolist ()) # ['¥ 137,580,000', 288,'¥ 477,708']

  • Answer # 2

    It is possible by creating a mask (an array of True or False) as shown below.

    mask = wb3.index! = 2
    print (wb3 [mask] .apply ('\ {:,}'. format))

    I haven't moved it at hand, but it should.