gpt4 book ai didi

python - 在 Pandas 中将列拆分为列表

转载 作者:行者123 更新时间:2023-12-01 02:03:59 25 4
gpt4 key购买 nike

我有一个以下示例数据帧:

| id   | lang      | text       |
_______________________________
| "1" | "en" | "text1" |
| "2" | "ua" | "text2" |
| "1" | "en" | "text3" |
| "2" | "en" | "text4" |
| "3" | "en" | "text5" |
| "4" | "ru" | "text6" |
| "4" | "en" | "text7" |
| "3" | "ua" | "text8" |

我需要按 ID 和语言对其进行分组,并将文本作为单独的列表输出。

上面 DataFrame 的输出应如下所示:

应该有一个唯一 ID 的列表:[1,2,3,4]

对于 lang 列中的每种语言,应该有一个单独的列表,其中包含来自 text 列的文本以及唯一 ID 列表的长度,在本例中,如果每个 ID 有多个文本,然后将它们连接起来(例如通过空格)。因为在示例 DF 中我们有 3 种语言:en、ua、ru;我们需要 3 个列表:

ids = [ 1,               2,        3,         4 ]  # <-- list of IDs for reference
en = ["text1 text3", "text4", "text5", "text7"]
ua = ["", "text2", "text8", "" ]
ru = ["", "", "", "text6"]

文本列表应与ID列表一样长,如果一个ID有多个文本,则应将它们连接起来,如果没有则写入一个空字符串。

到目前为止我有这个Python解决方案:

import pandas as pd
my_table = pd.read_csv("my_data.csv", delimiter="\t")

en = list()
ua = list()
ru = list()

# iterate over unique ids only
for single_id in list(my_table.cluster_id.unique()):

# append a concatenated list of all texts given id and lang
en.append(" ".join(list(
my_table[(my_table["id"]==unicode(id))&(my_table["lang"]==unicode("en"))]["text"]
)))

ua.append(" ".join(list(
my_table[(my_table["id"]==unicode(id))&(my_table["lang"]==unicode("ua"))]["text"]
)))

de.append(" ".join(list(
my_table[(my_table["id"]==unicode(id))&(my_table["lang"]==unicode("ru"))]["text"]
)))

这相当慢。有什么方法可以先在 Pandas 中进行过滤,然后以某种方式快速将其输出到单独的列表中?我需要 Python 列表作为输出。

编辑:这是在 Python 2.7 上

最佳答案

IIUC

#df.groupby(['id','lang']).text.apply(list).unstack(-2)
df.groupby(['id','lang']).text.apply(','.join).unstack(-2)

Out[384]:
id 1 2 3 4
lang
en text1,text3 text4 text5 text7
ru None None None text6
ua None text2 text8 None

如果你想成为“列表”(字典)

df.groupby(['id','lang']).text.apply(','.join).unstack(-2).T.fillna('').to_dict('l')
Out[386]:
{'en': ['text1,text3', 'text4', 'text5', 'text7'],
'ru': ['', '', '', 'text6'],
'ua': ['', 'text2', 'text8', '']}

对于 ID

df.groupby(['id','lang']).text.apply(','.join).unstack(-2).columns.tolist()
Out[388]: [1, 2, 3, 4]

关于python - 在 Pandas 中将列拆分为列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49258671/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com