DataFrame是一个二维数据结构,即数据以行和列的方式以表格形式对齐。
DataFrame特点:
pandas.DataFrame( data, index, columns, dtype, copy)
参数解释:
序号 | 参数和描述 |
---|---|
1 | 数据(data) 数据可以是各种形式,如ndarray、series、map、lists、dict、constants和另一个DataFrame。 |
2 | 索引(index) 用于行标签的索引,如果没有传递索引,则默认为np.arange(n)。 |
3 | 列标签(columns) 用于列标签的可选默认语法是np.arange(n),仅当没有传递索引时才成立。 |
4 | 数据类型(dtype) 每列的数据类型。 |
5 | 复制(copy) 如果默认值为False,则用于复制数据的命令(或其他命令)。 |
#import the pandas library and aliasing as pd
import pandas as pd
df = pd.DataFrame()
print df
data =[1,3,2,12]
df = pd.DataFrame(data)
print(df)
data = [['aa', 18], ['bb', 21], ['cc', 22.]]
df = pd.DataFrame(data,columns=['Name', 'Age'])
print(df)
data = {'Name':['aa', 'bb', 'cc'], 'Age': [18, 21., 22]}
df = pd.DataFrame(data)
print(df)
data = {'Name':['aa', 'bb', 'cc'], 'Age': [18, 21., 22]}
df = pd.DataFrame(data, index=['rank1', 'rank2', 'rank3'])
print(df)
data = [{"aa":18,'bb':21.}, {'aa':11, 'bb':81, 'cc':71}]
df = pd.DataFrame(data)
print(df)
data = [{"aa":18,'bb':21.}, {'aa':11, 'bb':81, 'cc':71}]
df = pd.DataFrame(data, index=['first', 'second'])
print(df)
data = [{"aa":18,'bb':21.}, {'aa':11, 'bb':81, 'cc':71}]
# With 2 columns indices, values same as dictionary keys
df = pd.DataFrame(data, index=['first', 'second'], columns=['aa', 'bb'])
print(df)
# With 2 columns indices, columns values with different dictionary keys
df1 = pd.DataFrame(data, index=['first', 'second'], columns=['aa', 'bb1'])
print(df1)
data = {
'one':pd.Series([1,9,12,8],index=['a','b','c','e']),
'two': pd.Series([8,12,1,2], index=['a','b','c','d'])
}
df = pd.DataFrame(data)
print(df)
data = {
'one':pd.Series([1,9,12,8],index=['a','b','c','e']),
'two': pd.Series([8,12,1,2], index=['a','b','c','d'])
}
df = pd.DataFrame(data)
print(df['one'])
# Adding a new column to an existing DataFrame object with column label by passing new series
print("Adding new DataFrame column by Passing a Series:")
df['three'] = pd.Series([10,29,81], index=['a', 'b','c'])
print(df)
df['four']=df['one'] + df['three']
print(df)
del(df['four'])
print(df)
data = {
'one':pd.Series([1,9,12,8],index=['a','b','c','e']),
'two': pd.Series([8,12,1,2], index=['a','b','c','d'])
}
df = pd.DataFrame(data)
row = df.loc['b']
print(row)
# index location from 0
row = df.iloc[3]
print(row)
# include start, exclude end
n_df = df[1:3]
print(n_df)
df = pd.DataFrame([[1,8]], columns=['a','b'])
df1 = pd.DataFrame([[2,9]], columns=['a', 'b'])
df = df.append(df1)
print(df)
···
df = pd.DataFrame([[1,8]], columns=[‘a’,‘b’])
df1 = pd.DataFrame([[2,9]], columns=[‘a’, ‘b’])
df = df.append(df1)
df = df.drop(0)
print(df)
···