pandas dataframe 新增单列和多列
dataframe 新增单列
assign方法
dataframe assign方法,返回一个新对象(副本),不影响旧dataframe对象
import pandas as pd
df = pd.DataFrame({
'col_1': [0, 1, 2, 3],
'col_2': [4, 5, 6, 7]
})
sLength = len(df['col_1'])
df2 = df.assign(col_3=pd.Series([8, 9, 10, 11]).values)
print(df)
print(df2)
结果展示:
col_1 col_2
0 0 4
1 1 5
2 2 6
3 3 7
col_1 col_2 col_3
0 0 4 8
1 1 5 9
2 2 6 10
3 3 7 11
简单的方法和insert方法
简单的方法df[‘col_3’] = pd.Series([8, 9, 10, 11])
insert方法 df.insert(loc=len(df.columns), column=“col_4”, value=[8, 9, 10, 11])
这种方式会对旧的dataframe新增列
import pandas as pd
df = pd.DataFrame({
'col_1': [0, 1, 2, 3],
'col_2': [4, 5, 6, 7]
})
df['col_3'] = pd.Series([8, 9, 10, 11])
print(df)
df.insert(loc=len(df.columns), column="col_4", value=[8, 9, 10, 11])
print(df)
dataframe 新增多列
list unpacking
import pandas as pd
import numpy as np
df = pd.DataFrame({
'col_1': [0, 1, 2, 3],
'col_2': [4, 5, 6, 7]
})
df['column_new_1'], df['column_new_2'], df['column_new_3'] = [np.nan, 'dogs', 3]
print(df)
结果展示:
col_1 col_2 column_new_1 column_new_2 column_new_3
0 0 4 NaN dogs 3
1 1 5 NaN dogs 3
2 2 6 NaN dogs 3
3 3 7 NaN dogs 3
DataFrame也可以一行匹配
df[['column_new_1', 'column_new_2', 'column_new_3']] = pd.DataFrame([[np.nan, 'dogs', 3]], index=df.index)
concat方法
df = pd.concat(
[
df,
pd.DataFrame(
[[np.nan, 'dogs', 3]],
index=df.index,
columns=['column_new_1', 'column_new_2', 'column_new_3']
)
], axis=1
)
join方法
df = df.join(pd.DataFrame(
[[np.nan, 'dogs', 3]],
index=df.index,
columns=['column_new_1', 'column_new_2', 'column_new_3']
))
join + 字典
df = df.join(pd.DataFrame(
{
'column_new_1': np.nan,
'column_new_2': 'dogs',
'column_new_3': 3
}, index=df.index
))
assign方法
df = df.assign(column_new_1=np.nan, column_new_2='dogs', column_new_3=3)
土方法
df['column_new_1'] = np.nan
df['column_new_2'] = 'dogs'
df['column_new_3'] = 3
还没有评论,来说两句吧...