【发布时间】:2020-12-28 21:00:27
【问题描述】:
我尝试了三种不同的方法将字符串值的列表(内容)添加到现有 df(all_df) 的新列中,但每次由于列表而出现一些错误。有 2 列进行比较如果相同,则复制内容。即它匹配两列并相应地分配值。匹配完成得很完美,但输出列表并没有以任何方式出现在 DF 中。
我搜索过,但找不到解决方案。请帮助。
content[]
for i in range(len(col1)):
for j in range(len(col2)):
a=(col1[i])[0:5]
b=(col2[j])[0:5]
if(a==b):
val=con[j]
break
else:
val="Daily Update"
content.append(val)
print(content)
#输出内容: """['动机帖', '意识帖', '意识帖', '产品帖', '节日帖', '每日更新', '节日帖', '一般帖', '产品帖' , 'Awareness Post', 'Motivation Post', 'Product Post', 'Motivation Post', 'Awareness Post', '每日更新', 'Product Post', 'Motivation Post', 'General Post', 'Product Post' , '节日邮报']"""
#(first approach)
all_df.insert(loc=0, column='Content Bucket', value=content)
"""error:Traceback (most recent call last):
File "C:/Users/Desktop/analytics/twitter/demo.py", line 43, in <module>
all_df.insert(loc=0, column='Content Bucket', value=content)
TypeError: insert() takes no keyword arguments
"""
#(second approach)
all_df['Content Bucket']=np.array(content)
"""error:Traceback (most recent call last):
File "C:/Users/Desktop/analytics/twitter/demo.py", line 45, in <module>
all_df['Content Bucket']=np.array(content)
TypeError: list indices must be integers or slices, not str
"""
#(third approach)
dftemp = pd.DataFrame(data=content, columns=["Content Bucket"])
dft=pd.concat(dftemp,all_df)
"""error:Traceback (most recent call last):
File "C:/Users/jeshal/Desktop/analytics/twitter/demo.py", line 47, in <module>
dft=pd.concat(dftemp,all_df)
File "C:\Users\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pandas\core\reshape\concat.py", line 271, in concat
op = _Concatenator(
File "C:\Users\\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pandas\core\reshape\concat.py", line 306, in __init__
raise TypeError(
TypeError: first argument must be an iterable of pandas objects, you passed an object of type "DataFrame"
"""
all_df.to_excel("mergedt.xlsx",index=False)
【问题讨论】:
-
发布打印结果(内容)
-
完成@gtomer 请看一下
-
要将列表作为行还是作为列添加到 DF 中?
-
作为@gtomer 列
标签: python-3.x pandas list numpy dataframe