join()在python中返回NaN值
我的系列中有一些int类型的值,我尝试将其与数据框连接起来,但该系列被添加为列,但值与预期不同,它们被“NaN”填充 这是我的密码join()在python中返回NaN值,python,pandas,numpy,dataframe,series,Python,Pandas,Numpy,Dataframe,Series,我的系列中有一些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(d
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)
如果只想添加一个新列,则不必使用
join()
new_df=df
新的_-df[‘添加的_系列’]=列表(s3)
输出:
Out[54]:
0 1 2 3 4 5添加了\u系列
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
或使用:
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
dataframe和序列的索引不匹配:一个是默认数字,另一个是r1、r2等。即使更改列名,仍然会得到相同的NAN。列名正常。序列的索引(行名称)与数据帧的索引不同。让他们一样。重置数据帧的索引或向序列中添加非默认索引。通过向序列中添加索引获得该索引。谢谢,但是没有其他方法可以在不手动指定索引的情况下添加值。我只是尝试将数据帧与序列连接起来。但是谢谢你。谢谢你的解决方案,但是有没有办法用join()实现同样的效果。谢谢,它正在工作。请您解释Cube()中的“WHO”参数,例如何时考虑哪个选项。
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