在数据框中添加列

时间:2019-01-30 02:52:51

标签: python pandas dataframe

DF中的行为

在向DF添加新列时看到无法解释的情况

import pandas as pd

d = {'one' : pd.Series([1, 2, 3], index=['a', 'b', 'c']),
      'two' : pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])}

df = pd.DataFrame(d)
print(df)
# Adding a new column to an existing DataFrame object with column label by passing new series

print ("Adding a new column by passing as Series:")
df['three']=pd.Series([10,20,30],index=['a','b','c'])
print(df)

print ("Adding a new column using the existing columns in DataFrame:")
print("print df['one']")
print(df['one'])
print("#print(df['two']")
print(df['two'])
print("#print df['three']")
df['three']
print("df['four']=df['one']+df['three']")
df['four']=df['one']+df['three']
#print(df)
print(df)

实际结果:

one  two
a  1.0    1
b  2.0    2
c  3.0    3
d  NaN    4

通过作为系列传递来添加新列:

   one  two  three
a  1.0    1   10.0
b  2.0    2   20.0
c  3.0    3   30.0
d  NaN    4    NaN

使用DataFrame中的现有列添加新列:

print(df ['one']):

a    1.0
b    2.0
c    3.0
d    NaN
Name: one, dtype: float64

print(df ['two']):

a    1
b    2
c    3
d    4
Name: two, dtype: int64

print(df ['three']):

nothing

df ['four'] = df ['one'] + df ['three']

  one  two  three  four
a  1.0    1   10.0  11.0
b  2.0    2   20.0  22.0
c  3.0    3   30.0  33.0
d  NaN    4    NaN   NaN

问题

为什么在打印df [“ three”]时我什么都没有?

0 个答案:

没有答案
相关问题