简体   繁体   English

如何使用Python将列表的值附加到DataFrame列的值?

[英]How can I append the values of a list to the values of a DataFrame column using Python?

I have this DataFrame: 我有这个DataFrame:

df=pd.DataFrame.from_items([('id', [14, 49, 21]), 
                     ('parameter', [12, 23, 11])])

And I have this list: 我有这个清单:

[8, 1, 3]
<class 'list'>

I want to append the list values to each value of the column id of the dataframe df, I want something like this: 我想将列表值附加到数据框df的列ID的每个值,我想要这样的东西:

   id       parameter
0  148         12
1  491         23
2  213         11

How can I do it? 我该怎么做?

You can try like so: 您可以这样尝试:

import pandas as pd

df = pd.DataFrame.from_items([('id', [14, 49, 21]), ('parameter', [12, 23, 11])])
l = iter([8, 1, 3])

df.id = df.id.apply(lambda x: str(x)+str(next(l))).astype(int)
print df

Output: 输出:

    id  parameter
0  148         12
1  491         23
2  213         11

Using zip works: 使用zip作品:

import pandas as pd
df = pd.DataFrame.from_items([('id', [14, 49, 21]), ('parameter', [12, 23, 11])])
l = [8, 1, 3]
df['id'] = [int(''.join([str(j) for j in i])) for i in zip(df['id'], l)]

and the resulting df is: 所得的df为:

>>> df
    id  parameter
0  148         12
1  491         23
2  213         11
import pandas as pd

df = pd.DataFrame.from_items([('id', [14, 49, 21]), ('parameter', [12, 23, 11])])

lista = [8,1,3]

for i in range(len(lista)):
    df['id'][i] = int(str(df['id'][i]) + str(lista[i]))

print df

   id  parameter
0  148         12
1  491         23
2  213         11

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从列表值中替换 DataFrame 值? -Python - How can I replace DataFrame values from List values? -python 如何将 append 列转换为 DataFrame 以收集 Python 中另一个 DataFrame 的值? - How to append a column to a DataFrame that collects values of another DataFrame in Python? Python - 初学者帮助 - 如何将 append 多个值添加到一个列表中? - Python - beginner help - How can I append multiple values to a list? 如何使用 Python 根据匹配的键值在字典列表中附加其他数据 - How can I append other data in a list of dictionaries based on matching key values using Python 如何使用 Python 中的列表、数组或循环将 append 行值添加到 Google 工作表? - How can I append row values to a Google sheet using a list, array or loop in Python? 将列表值附加到 DataFrame 列数据 - Append List values to DataFrame Column data 将数据框列中的值附加到列表 - Append values from dataframe column to list 如何遍历数据框,创建新列并在python中为其添加值 - How to loop through a dataframe, create a new column and append values to it in python 不能使用条件语句将 append 列值添加到列表中 - Can't append column values to a list using a conditional statement 如何使用基于条件的值将 append 列到 dataframe - How to append a column to a dataframe with values based on condition
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM