pandas笔记--(1)--[DataFrames]
2017-03-16 本文已影响0人
FengBli
reference course at datacamp
- 读取csv文件到dataframe中
- 对dataframe的复制
- 对dataframe中的数据赋予新的列名/更改列名
- 对dataframe添加新的列名和列数据
import pandas as pd
gold = pd.read_csv("No_1.csv")
sliver = pd.read_csv("No_2.csv")
bronze = pd.read_csv("No_3.csv")
# Make a copy of gold: medals
medals = gold.copy()
# Create list of new column labels: new_labels
new_labels = ['NOC', 'Country', 'Gold']
# Rename the columns of medals using new_labels
medals.columns = new_labels
# Add columns 'Silver' & 'Bronze' to medals
medals['Silver'] = silver['Total']
medals['Bronze'] = bronze['Total']
- 使用glob函数获取类似文件名列表
from glob import glob
dataframes = []
filenames = glob("No_*.csv")
for filename in filenames:
dataframes.append(pd.read_csv(filename))
# Import pandas
import pandas as pd
# Read 'monthly_max_temp.csv' into a DataFrame: weather1
weather1 =pd.read_csv("monthly_max_temp.csv", index_col="Month")
# Print the head of weather1
print(weather1.head())
# Sort the index of weather1 in alphabetical order: weather2
weather2 = weather1.sort_index()
# Print the head of weather2
print(weather2.head())
# Sort the index of weather1 in reverse alphabetical order: weather3
weather3 = weather1.sort_index(ascending=False)
# Print the head of weather3
print(weather3.head())
# Sort the index of weather1 numerically using the values of 'Max TemperatureF': weather4
weather4 = weather1.sort_values('Max TemperatureF')
# Print the head of weather4
print(weather4.head())
- reindex()
# Import pandas
import pandas as pd
# Reindex weather1 using the list year: weather2
weather2 = weather1.reindex(year)
# Print weather2
print(weather2)
# Reindex weather1 using the list year with forward-fill: weather3
# .ffill() method to replace the null values with the last preceding non-null value.
weather3 = weather1.reindex(year).ffill()
# Print weather3
print(weather3)