我想在pandas数据框的开头添加一列1,该数据框是从外部数据文件“ex1data1.txt'”创建的。我写了以下代码。问题是print(data)
命令最终返回None。这段代码有什么问题?我希望data
成为pandas数据帧。 raw_data
和X0_
很好,我打印过它们。
import numpy as np
import pandas as pd
raw_data = pd.read_csv('ex1data1.txt', header= None, names= ['x1','y'])
X0_ = np.ones(len(raw_data))
idx = 0
data = raw_data.insert(loc=idx, column='x0', value=X0_)
print(data)
答案 0 :(得分:2)
另一种解决方案可能如下所示:
import numpy as np
import pandas as pd
raw_data = pd.read_csv('ex1data1.txt', header= None, names= ['x1','y'])
raw_data.insert(loc=0, column='x0', value=1.0)
print(raw_data)
答案 1 :(得分:1)
您可以使用pd.DataFrame.insert
,但请注意此解决方案已就绪,无需重新分配。您可能还需要将dtype显式设置为int
:
df = pd.DataFrame([[1, 2, 3], [4, 5, 6]],
columns=['col1', 'col2', 'col3'])
arr = np.ones(len(df.index), dtype=int)
idx = 0
df.insert(loc=idx, column='col0', value=arr)
print(df)
col0 col1 col2 col3
0 1 1 2 3
1 1 4 5 6
一个简洁的解决方案是简单地添加一行并移动到列到数据帧的开头。这是一个完整的例子:
df = pd.DataFrame([[1, 2, 3], [4, 5, 6]],
columns=['col1', 'col2', 'col3'])
df['col0'] = 1 # adds column to end of dataframe
cols = [df.columns[-1]] + df.columns[:-1].tolist() # move last column to front
df = df[cols] # apply new column ordering
print(df)
col0 col1 col2 col3
0 1 1 2 3
1 1 4 5 6