【问题标题】:join() returning NaN values in pythonjoin() 在 python 中返回 NaN 值
【发布时间】:2020-10-25 12:46:43
【问题描述】:

我的系列中有一些 int 类型值,我尝试将其与数据框连接起来,但系列被添加为列,但值与预期不符,它们填充了“NaN” 这是我的代码

s3=Series(np.arange(6))
s3.name="added_series"
np.random.seed(25)
df=DataFrame(np.random.rand(36).reshape((6,6)),index=['r1','r2','r3','r4','r5','r6'])
dfadd=DataFrame.join(df,s3)

【问题讨论】:

  • dataframe和series的索引不匹配:一个是默认数值,另一个是r1、r2等
  • 即使更改了列名,仍然得到相同的 NaN。
  • 列名没问题。系列的索引(行名)与数据框的索引不同。使它们相同。要么重置数据框的索引,要么为系列添加一个非默认索引。
  • 通过向系列添加索引得到它。谢谢,但是没有其他方法可以在不手动指定索引的情况下添加值。

标签: python pandas numpy dataframe series


【解决方案1】:
import pandas as pd

pd.concat([df.reset_index(), DataFrame(s3)], axis=1).set_index("index")

或使用:

df.reset_index().join(DataFrame(s3), how="inner").set_index("index")

输出是:

Out[29]: 
              0         1         2         3         4         5  added_series
index                                                                          
r1     0.870124  0.582277  0.278839  0.185911  0.411100  0.117376             0
r2     0.684969  0.437611  0.556229  0.367080  0.402366  0.113041             1
r3     0.447031  0.585445  0.161985  0.520719  0.326051  0.699186             2
r4     0.366395  0.836375  0.481343  0.516502  0.383048  0.997541             3
r5     0.514244  0.559053  0.034450  0.719930  0.421004  0.436935             4
r6     0.281701  0.900274  0.669612  0.456069  0.289804  0.525819             5

【讨论】:

  • 感谢您的解决方案,但有什么方法可以通过 join() 实现相同的效果。
  • 谢谢,它正在工作。请您解释一下 join() 中的 'how' 参数,比如何时考虑哪个选项。
  • 您可以阅读这份完整而清晰的文档:pandas.pydata.org/pandas-docs/stable/reference/api/…
【解决方案2】:

如果只想添加新列,则不必使用join()

new_df = df
new_df['added_series'] = list(s3)

输出:

Out[54]:
0   1   2   3   4   5   added_series
r1  0.870124    0.582277    0.278839    0.185911    0.411100    0.117376    0
r2  0.684969    0.437611    0.556229    0.367080    0.402366    0.113041    1
r3  0.447031    0.585445    0.161985    0.520719    0.326051    0.699186    2
r4  0.366395    0.836375    0.481343    0.516502    0.383048    0.997541    3
r5  0.514244    0.559053    0.034450    0.719930    0.421004    0.436935    4
r6  0.281701    0.900274    0.669612    0.456069    0.289804    0.525819    5

【讨论】:

  • 我刚刚尝试将数据框与系列连接起来。但谢谢你。
猜你喜欢
  • 2022-01-24
  • 1970-01-01
  • 1970-01-01
  • 2019-06-15
  • 2018-04-29
  • 2019-06-20
  • 1970-01-01
  • 2021-05-10
  • 1970-01-01
相关资源
最近更新 更多