将一个将一个DataFrame中的一列(行),插入到另一个中的一列(行),插入到另一个DataFrame
中中
原始数据:
import pandas as pd
import numpy as np
data = {'a': [4, 6, 5, 7, 8],
'b': ['w', 't', 'y', 'x', 'z'],
'c': [1, 0, 6, -5, 3],
'd': [3, 4, 7, 10, 8],
}
df = pd.DataFrame(data, index=['one', 'two', 'three', 'four', 'five'])
print(df)
# a b c d
# one 4 w 1 3
# two 6 t 0 4
# three 5 y 6 7
# four 7 x -5 10
# five 8 z 3 8
new_df = pd.DataFrame({'a': [1, 2, 3, 3, 4],
'b': [1, 2, 3, 3, 4],
'c': [22, 33, 22, 44, 66],
'd': [1, 2, 3, 3, 4] },
index=['one', 'two', 'three', 'four', 'five'])
print(new_df)
# a b c d
# one 1 1 22 1
# two 2 2 33 2
# three 3 3 22 3
# four 3 3 44 3
# five 4 4 66 4
插入列插入列
方法一方法一
new_df['newcol'] = df['b'] print(new_df)
# a b c d newcol
# one 1 1 22 1 w
# two 2 2 33 2 t
# three 3 3 22 3 y
# four 3 3 44 3 x
# five 4 4 66 4 z
方法二方法二
new_df['newcol'] = df.pop('b')
print(new_df)
# a b c d newcol
# one 1 1 22 1 w
# two 2 2 33 2 t
# three 3 3 22 3 y
# four 3 3 44 3 x
# five 4 4 66 4 z
方法三方法三
new_df.insert(2, 'newcol', df['b'].values)
print(new_df)
# a b newcol c d
# one 1 1 w 22 1
# two 2 2 t 33 2
# three 3 3 y 22 3
# four 3 3 x 44 3
# five 4 4 z 66 4
评论0