[英]Pandas adding values into the dataframe
Here is my code where I'm trying to add/append new values to the third column:这是我尝试将新值添加/追加到第三列的代码:
file = 'excel_name.xlsx'
df = pd.read_excel(file, engine='openpyxl')
print(df)
df.insert(3, 'sub', [1, 7, 4, 1])
print('test', df)
the output of print(df):打印(df)的输出:
name ... sub
0 test1 ... NaN
1 test2 ... NaN
2 test3 ... NaN
3 test4 ... NaN
What I want to do:我想做的事:
name ... sub
0 test1 ... 1
1 test2 ... 7
2 test3 ... 4
3 test4 ... 1
you can do like this:你可以这样做:
import pandas as pd
df = pd.read_excel('~/Downloads/excel_name.xlsx')
array = [1,4,7,1]
df['sub'] = array
print(df)
# output
name sub
0 test1 1
1 test2 4
2 test3 7
3 test4 1
Warning: Your array and the number of rows in your excel should match.警告:您的数组和 Excel 中的行数应该匹配。
Edit: Your code also should work, please check the index which you are trying to add, if the last index of the df goes beyond three then it will throw error.编辑:您的代码也应该可以工作,请检查您要添加的索引,如果 df 的最后一个索引超过三,那么它将引发错误。
you can use this.你可以用这个。 This will work for both even and uneven length of list which doesn't match for the length of columns这将适用于与列的长度不匹配的列表的均匀和不均匀长度
l = [1,7,4,1]
df.loc[range(len(l)),'sub'] = l
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.