gpt4 book ai didi

pandas - pandas 数据框中的第一列不是列?

转载 作者:行者123 更新时间:2023-12-02 02:48:25 26 4
gpt4 key购买 nike

我有一个数据框:

>>df
Column1 Column2
vo1
102 0.023002 0
301 3571.662104 0
302 1346.910261 0
...

所以有三列?但是:

>>df.dtypes
Column1 float64
Column2 float64
dtype: object

那么它有两列?第一个 (vo) 叫什么?我想使用它进行合并,但是当我这样做时,我收到错误消息,说没有名为 vo 的列。

最佳答案

它叫做index,检查它:

print (df.index)
Int64Index([102, 301, 302], dtype='int64', name='vo_11')

另请检查docs :

The axis labeling information in pandas objects serves many purposes:

-Identifies data (i.e. provides metadata) using known indicators, important for analysis, visualization, and interactive console display
-Enables automatic and explicit data alignment
-Allows intuitive getting and setting of subsets of the data set

如果需要merge通过两个 DataFrames 的索引:

df = pd.merge(df1, df2, left_index=True, right_index=True)

或者使用concat :

df = pd.concat([df1, df2], axis=1) 

注意:

为了匹配相同类型的需要索引 - intobject(显然 string)

示例:

df1 = pd.DataFrame({
'Column1': {302: 10, 301: 21, 102: 2},
'Column2': {302: 0, 301: 0, 102: 0}})
print (df1)
Column1 Column2
102 2 0
301 21 0
302 10 0

df2 = pd.DataFrame({
'Column1': {302: 4, 301: 5, 304: 6},
'Column2': {302: 0, 301: 0, 304: 0}})
print (df2)
Column1 Column2
301 5 0
302 4 0
304 6 0
<小时/>
df = pd.merge(df1, df2, left_index=True, right_index=True)
print (df)
Column1_x Column2_x Column1_y Column2_y
301 21 0 5 0
302 10 0 4 0

df = pd.merge(df1, df2, left_index=True, right_index=True, how='outer')
print (df)
Column1_x Column2_x Column1_y Column2_y
102 2.0 0.0 NaN NaN
301 21.0 0.0 5.0 0.0
302 10.0 0.0 4.0 0.0
304 NaN NaN 6.0 0.0

df = pd.concat([df1, df2], axis=1)
print (df)
Column1 Column2 Column1 Column2
102 2.0 0.0 NaN NaN
301 21.0 0.0 5.0 0.0
302 10.0 0.0 4.0 0.0
304 NaN NaN 6.0 0.0

df = pd.concat([df1, df2], axis=1, join='inner')
print (df)
Column1 Column2 Column1 Column2
301 21 0 5 0
302 10 0 4 0

关于pandas - pandas 数据框中的第一列不是列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41265138/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com