Si vous voulez une solution laide qui fonctionne aussi ... voici une fonction que j'ai créée qui trouve des colonnes qui contiennent seulement des chaînes, et renvoie la df moins ces lignes. (puisque votre df n'a qu'une seule colonne, vous aurez juste un dataframe contenant une colonne avec tous les dicts). Ensuite, à partir de là, vous voudrez utiliser df = json_normalize(df['A'].values)
au lieu de simplement df = json_normalize(df['A'])
.
Pour dataframe une seule colonne ...
import pandas as pd
import numpy as np
from pandas.io.json import json_normalize
def delete_strings(df):
nrows = df.shape[0]
rows_to_keep = []
for row in np.arange(nrows):
if type(df.iloc[row,0]) == dict:
rows_to_keep.append(row) #add the row number to list of rows
#to keep if the row contains a dict
return df.iloc[rows_to_keep,0] #return only rows with dicts
df = pd.DataFrame({'A': ["hello","world",{"a":5,"b":6,"c":8},"usa","india",
{"a":9,"b":10,"c":11}]})
df = delete_strings(df)
df = json_normalize(df['A'].values)
print(df)
#0 {'a': 5, 'b': 6, 'c': 8}
#1 {'a': 9, 'b': 10, 'c': 11}
Pour une df plusieurs colonnes (fonctionne également avec une seule colonne df):
def delete_rows_of_strings(df):
rows = df.shape[0] #of rows in df
cols = df.shape[1] #of coluns in df
rows_to_keep = [] #list to track rows to keep
for row in np.arange(rows): #for every row in the dataframe
#num_string will count the number of strings in the row
num_string = 0
for col in np.arange(cols): #for each column in the row...
#if the value is a string, add one to num_string
if type(df.iloc[row,col]) == str:
num_string += 1
#if num_string, the number of strings in the column,
#isn't equal to the number of columns in the row...
if num_string != cols: #...add that row number to the list of rows to keep
rows_to_keep.append(row)
#return the df with rows containing at least one non string
return(df.iloc[rows_to_keep,:])
df = pd.DataFrame({'A': ["hello","world",{"a":5,"b":6,"c":8},"usa","india"],
'B' : ['hi',{"a":5,"b":6,"c":8},'sup','america','china']})
# A B
#0 hello hi
#1 world {'a': 5, 'b': 6, 'c': 8}
#2 {'a': 5, 'b': 6, 'c': 8} sup
print(delete_rows_of_strings(df))
# A B
#1 world {'a': 5, 'b': 6, 'c': 8}
#2 {'a': 5, 'b': 6, 'c': 8} sup
C'est JSON pas une fois que vous avez fait votre df, c'est un dict. Mais ça me tient occupé à essayer de garder sélectivement ces colonnes à coup sûr :) – roganjosh
Oui, par json je voulais dire dict uniquement. Toute idée comment puis-je supprimer toutes les lignes qui contiennent des chaînes simples comme "bonjour", "monde", etc –
Veuillez répondre à cette question https://stackoverflow.com/questions/46856988/np-isreal-behavior-different-in- pandas-dataframe-and-numpy-array – Wen