11. Study + Practice

import numpy as np
import pandas as pd

Look at the transpose
df = pd.DataFrame(np.random.rand(16).reshape(8.2) * 100, columns=['a'.'b'])

print(df.head(2))
print(df.tail())

# transpose
print(df.T)


# Add and modify
df = pd.DataFrame(np.random.rand(16).reshape(4.4), columns=['a'.'b'.'c'.'d'])
df['e'] = 10
print(df)
df.loc[4] = 20
print(df)

df[['a'.'c']] = 5
print(df)

df.iloc[::2] = 101
print(df)

# delete column does not change the original data
del df['e']
print(df)

Delete rows to change the original data
print(df.drop(0))

print(df.drop([1.2]))

# drop column alter data
print(df.drop(['d'], axis=1))

# alignment
df1 = pd.DataFrame(np.random.rand(16).reshape(4.4), columns=['a'.'b'.'c'.'d'])
df2 = pd.DataFrame(np.random.rand(16).reshape(8.2), columns=['a'.'b'])
print(df1 + df2)

# sort
Sort by value
df1 = pd.DataFrame(np.random.rand(16).reshape(4.4) *100, columns=['a'.'b'.'c'.'d'])
# a column in default ascending order
print(df1.sort_values(['a'], ascending=True)) # ascending
print(df1.sort_values(['a'], ascending=False)) # descending
# multirow sort
print(df1.sort_values(['a'.'c']))

Sort by index by default ascending
print(df1.sort_index())
Copy the code