我有三个csv文件,我们可以调用a,b和c。文件a具有包括邮政编码的地理信息。文件b有统计数据。文件c只有邮政编码。将对象转换为熊猫字符串后的关键错误?
我用大熊猫a
和b
转换为我用于连接上,这是那两个dataframes(intermediate_df
)之间的共享列信息dataframes(a_df
和b_df
)。读取文件c
并将其转换为具有整数类型的zipcode的数据帧。我必须将其转换为字符串,以便将zipcode不视为整数。但是,c_df
将该列转换为字符串后将其视为对象,这意味着我无法在c_df
和intermediate_df之间进行连接以创建final_df。
为了说明我的意思:
a_data = pd.read_csv("a.csv")
b_data = pd.read_csv("b.csv", dtype={'zipcode': 'str'})
a_df = pd.DataFrame(a_data)
b_df = pd.DataFrame(b_data)
# file c conversion
c_data = pd.read_csv("slcsp.csv", dtype={'zipcode': 'str'})
print ("This is c data types: ", c_data.dtypes)
c_conversion = c_data['zipcode'].apply(str)
print ("This is c_conversion data types: ", c_conversion.dtypes)
c_df = pd.DataFrame(c_conversion)
print ("This is c_df data types: ", c_df.dtypes)
# Joining on the two common columns to avoid duplicates
joined_ab_df = pd.merge(a_df, a_df, on =['state', 'area'])
# Dropping columns that are not needed anymore
ab_for_analysis_df = joined_ab.drop(['county_code','name', 'area'], axis=1)
# Time to analyze this dataframe. Let's pick out only the silver values for
a specific attribute
silver_only_df = (ab_for_analysis_df[filtered_df.metal_name == 'Silver'])
# Getting second lowest value of silver only
sorted_silver = silver_only_df.groupby('zipcode')['rate'].nsmallest(2)
sorted_silver_df = sorted_silver.to_frame()
print ("We cleaned up our data. Let's join the dataframes.")
print ("Final result...")
print (c_df.dtypes)
final_df = pd.merge(sorted_silver_df,c_df, on ='zipcode')
这是我们运行之后得到:
This is c_data types: zipcode object
rate float64
dtype: object
This is c_conversion_data types: object
This is c_df data types: zipcode object
dtype: object
zipcode object
dtype: object
We cleaned up our data. Let's join the dataframes.
This is the final result...
KeyError: 'zipcode'
任何想法,为什么它改变了数据类型和我怎么那么解决它,所以它所有最后加入?
你可以添加'打印(c_df.columns)'和'打印(sorted_silver_df.columns)' – Dark
所以倒数第二行:'打印(c_df.dtypes)'也不打印?这是奇怪的。我建议使用ipython/jupyter和'%debug'魔术功能,这样你可以逐步处理这些错误。 –
这是一个奇怪的问题。 @AndyHayden。打印c_df.dtypes工程虽然它给出奇怪的结果 –