Python教程

Python: panda

本文主要是介绍Python: panda,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

 

  1. import pandas as pd
    
    df = pd.DataFrame(data={'id': [1, 2, 3], 'name': ['a', 'b', 'c']})
    print(df)
    df.to_excel('z.xlsx')

     

     

  2. import pandas as pd
    
    df = pd.DataFrame(data={'id': [1, 2, 3], 'name': ['a', 'b', 'c']})
    df = df.set_index('id')
    print(df)
    df.to_excel('z.xlsx')

     

     

  3. import pandas as pd
    
    dataFrame = pd.read_excel('people.xlsx', header=1, index_col='ID')
    dataFrame.columns = ['type', 'title', 'firstName', 'middleName', 'lastName']
    # dataFrame.columns = ['id', 'type', 'title', 'firstName', 'middleName', 'lastName']
    print(dataFrame.shape)
    print(dataFrame.columns)
    print(dataFrame.head(3))
    print('~' * 80)
    print(dataFrame.tail())
    
    # dataFrame.set_index('ID', inplace=True)
    
    dataFrame.to_excel('z.xlsx')

     

  4. import pandas as pd
    
    dataFrame = pd.read_excel('people.xlsx', header=1)
    dataFrame.columns = ['id', 'type', 'title', 'firstName', 'middleName', 'lastName']
    print(dataFrame.shape)
    print(dataFrame.columns)
    print(dataFrame.head(3))
    print('~' * 80)
    print(dataFrame.tail())
    
    dataFrame.set_index('id', inplace=True)
    
    dataFrame.to_excel('z.xlsx')

     

     

     

     

  5. import pandas as pd
    
    d = {'x': 5, 'y': 55, 'z': 555}
    s1 = pd.Series(d)
    
    s2 = pd.Series(data=[5, 55, 666], index=['a', 'b', 'c'])

     

  6. column
    import pandas as pd
    
    s1 = pd.Series([1, 2, 3], index=[1, 2, 3], name='A')
    s2 = pd.Series([11, 22, 33], index=[1, 2, 3], name='B')
    s3 = pd.Series([111, 222, 333], index=[1, 2, 3], name='C')
    
    dataFrame = pd.DataFrame({s1.name: s1, s2.name: s2, s3.name: s3})
    print(dataFrame)

     

     

  7. import pandas as pd
    from datetime import date, timedelta
    
    book = pd.read_excel('book.xlsx', skiprows=3, usecols='c:f', dtype={'ID': str})
    print(book)
    # book['ID'].at[0] = 55
    d = date(2022, 5, 6)
    
    
    def cal_date(d: date, month: int):
        year_delta = month // 12
        m = d.month + month % 12
        if m > 12:
            year_delta += m // 12
            m = m % 12
        return date(d.year + year_delta, m, d.day)
    
    
    for i in book.index:
        # book['ID'].at[i] = i + 1
        book.at[i, 'ID'] = i + 1
        book['InStore'].at[i] = 'Y' if i % 2 else 'N'
        # book['Date'].at[i] = d + timedelta(days=i)
        # book['Date'].at[i] = date(d.year + i, d.month, d.day)
        book['Date'].at[i] = cal_date(d, i)
    print(book['ID'], type(book['ID']))
    print(book)
    book.set_index('ID', inplace=True)
    book.to_excel('z.xlsx')
    
    for i in book.index:
        print(i)

     

这篇关于Python: panda的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!