繁体   English   中英

如何在 Python 中将基于熊猫字符串的 DataFrame 转换为基于列表/元组的 DataFrame

[英]How to turn a pandas-string-based DataFrame to list/tuple based DataFrame in Python

我已经根据我加载的 CSV 文件构建了一个 DataFrame。 dataframe 大约有 60 行和 7 列。 此时 DF 中的所有对象都是字符串。

这就是它现在的样子: DF

dataframe 稍后将被输入 DNN,因此我需要 DF 中的每个 object 都是元组或列表(我更喜欢元组,但我想同时使用它以防万一)。

如何拆分字符串中的值以便将它们制成元组?

这是我的代码:

import pandas as pd
import datetime
from os import listdir


filepaths = [f for f in listdir("C:/Users/user/PycharmProjects/NDVI/data/") if f.endswith('.csv')]
df = pd.concat(map(pd.read_csv, filepaths))

df_v = pd.DataFrame(columns=['S2T0', 'S3T0', 'S3T1', 'S3T2', 'S3T4', 'S3T5', 'S2VAL'])
num_columns = len(df_v.columns)
row = 0


while row < len(df)-7:
    temp_data = {'S2T0': [df.iloc[row, 3].replace('[', '').replace(']', '')],
                 'S3T0': [df.iloc[row+1, 3].replace('[', '').replace(']', '')],
                 'S3T1': [df.iloc[row+2, 3].replace('[', '').replace(']', '')],
                 'S3T2': [df.iloc[row+3, 3].replace('[', '').replace(']', '')],
                 'S3T4': [df.iloc[row+4, 3].replace('[', '').replace(']', '')],
                 'S3T5': [df.iloc[row+5, 3].replace('[', '').replace(']', '')],
                 'S2VAL': [df.iloc[row+6, 3].replace('[', '').replace(']', '')]}
    temp_df = pd.DataFrame(temp_data)
    row += 7
    df_v = df_v.append(temp_df, ignore_index=True)


print(df_v.loc[0, 'S2T0']) #I did this to see the structure of one object in the DF
df_v.loc[:, :] = df_v.loc[:, :].apply(split, ", ")
print(df_v.loc[0, 'S2T0']) #Was hoping the split will work...

我得到这个异常: NameError: name 'split' is not defined (obviously because this is not the proper use of split..)

顺便说一句:如果您有任何比我更优雅的方式来清除 '[' & ']' 并构建 df_v - 我会很高兴听到。

请注意:由于缺少数据,我的一些对象是“[]”。 我需要传递空列表\元组或 NULL (两者都很好)

对于您遇到的拆分问题,没有拆分function 字符串有一种拆分方法 你可以做的是传递一个 lambda function 然后返回将方法应用到每一行中的字符串的每个结果。

此外,使用如下所示的applymap应该可以让您将 function 应用于 DataFrame 中的所有单元格。

df_v = df_v.applymap(lambda x: x.split(", ") if x!="" else [])

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM