【问题标题】:Pandas dataframe how to replace single column with multiple熊猫数据框如何用多个替换单列
【发布时间】:2020-11-15 06:34:37
【问题描述】:

例如,我有一个如下数据框:

col1 col2 col3
0    2    1

我想替换它以便

{0: [a,b], 1: [c,d], 2: [e, f]}

所以我想最终得到这样的数据框:

col1 col1b col2 col2b col3 col3b
a    b     e    f     c    d

我想在转换后将这些数据输入到 tensorflow 中,所以如果 tensorflow 可以接受,下面的输出也可能是可以接受的?

col1  col2  col3
[a,b] [e,f] [c,d]

以下是我当前的代码:

field_names = ["elo", "map", "c1", "c2", "c3", "c4", "c5", "e1", "e2", "e3", "e4", "e5", "result"]
df_train = pd.read_csv('input/match_results.csv', names=field_names, skiprows=1, usecols=range(2, 13))

for count in range(1, 6):
    str_count = str(count)
    df_train['c' + str_count] = df_train['c' + str_count].map(champ_dict)

【问题讨论】:

  • 好的,所以只需 map
  • 你需要添加一个更好的例子,这些列中的值会发生什么?你想要重复还是 NaN ?就个人而言,我认为这对于多索引列结构来说是一个很好的案例。无论如何,请参阅 minimal reproducible exampleHow to Ask
  • 删除标签machine-learningartificial-intelligence,因为它们与问题无关。
  • @Manakin 我在 OP 中添加了列。
  • @roganjosh 我知道我可以使用 map 但如何让它扩大列数?我最终将其输入到 tensorflow 中,所以我可以将它们映射为每列是一个数组而不是每列一个值,或者 tensorflow 不接受吗?到目前为止,每次我运行 tensorflow 时,它似乎只需要每列的整数而不是整数数组。

标签: python pandas tensorflow


【解决方案1】:

IIUC,您可以使用 .stack .map.cumcount 来重塑您的数据框和索引。

import pandas as pd
from string import ascii_lowercase

col_dict = dict(enumerate(ascii_lowercase))
map_dict = {0: ['a','b'], 1: ['c','d'], 2: ['e', 'f']}

s = df.stack().map(map_dict).explode().reset_index()
s['level_1'] = s['level_1'] +  s.groupby(['level_1','level_0']).cumcount().map(col_dict)




df_new = s.set_index(['level_0','level_1']).unstack(1).droplevel(0,1).reset_index(drop=True)

print(df_new)

level_1  col1a col1b col2a col2b col3a col3b
0           a     b     e     f     c     d

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-11
    • 2022-07-27
    • 2021-05-27
    • 2022-06-24
    • 2023-03-12
    • 2022-01-11
    • 2020-10-21
    • 1970-01-01
    相关资源
    最近更新 更多