【问题标题】:Reshaping 4*1 dataframe into 2*2 dataframe将 4*1 数据帧重塑为 2*2 数据帧
【发布时间】:2019-11-16 15:58:37
【问题描述】:

我有如下数据数据框

df_testcase = pd.DataFrame(['16SCSE102014','15/03/2019','16SCSE101350','15/03/2019'])

Initial dataframe

我需要将其转换为 2*2 数据帧

Expected dataframe

有人可以帮忙吗? 谢谢。

【问题讨论】:

标签: python pandas dataframe reshape data-manipulation


【解决方案1】:

你真的应该包括一个你正在谈论的例子,并遵循 cmets 中的建议..

至于你在说什么:

# If res is your (4,1) DataFrame, you can just do
res = df2.values.reshape(2,2)
df = pd.DataFrame(res)

【讨论】:

  • 谢谢。下次我会注意的。这解决了我的问题。
【解决方案2】:

我不确定是否有使用 pandas 数据框的简单方法来做到这一点。但是你可以使用 numpy 来做到这一点:

import pandas as pd
import numpy as np
df = pd.DataFrame({'the_only_column':[1,'a',2,'b',3,'c']})

np_array = np.array(df['the_only_column'])
np_array = np.reshape(np_array, (np_array.shape[0]//2, 2))

df = pd.DataFrame(np_array, columns=['new_column_name', 'other_column_name'])
print(df)

输出是:

  new_column_name other_column_name
0               1                 a
1               2                 b
2               3                 c

【讨论】:

    猜你喜欢
    • 2021-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-03
    • 1970-01-01
    • 2021-05-01
    • 1970-01-01
    相关资源
    最近更新 更多