developer tip

Python pandas는 셀에 목록을 삽입합니다.

optionbox 2020. 10. 19. 07:58
반응형

Python pandas는 셀에 목록을 삽입합니다.


목록 'abc'와 데이터 프레임 'df'가 있습니다.

abc = ['foo', 'bar']
df =
    A  B
0  12  NaN
1  23  NaN

목록을 셀 1B에 삽입하고 싶으므로이 결과를 원합니다.

    A  B
0  12  NaN
1  23  ['foo', 'bar']

할 수 있을까요?

1) 이것을 사용하는 경우 :

df.ix[1,'B'] = abc

다음과 같은 오류 메시지가 나타납니다.

ValueError: Must have equal len keys and value when setting with an iterable

두 개의 요소가있는 목록을 셀이 아닌 행 / 열에 삽입하려고하기 때문입니다.

2) 이것을 사용하는 경우 :

df.ix[1,'B'] = [abc]

그런 다음 'abc'목록 ( [['foo', 'bar']]) 인 요소가 하나만있는 목록을 삽입합니다 .

3) 이것을 사용하는 경우 :

df.ix[1,'B'] = ', '.join(abc)

그런 다음 foo, bar목록이 아닌 문자열 (( )을 삽입 합니다.

4) 이것을 사용하는 경우 :

df.ix[1,'B'] = [', '.join(abc)]

그런 다음 목록을 삽입하지만 하나의 요소 ( ['foo, bar']) 만 있고 내가 원하는대로 두 개는 없습니다 ( ['foo', 'bar']).

도와 주셔서 감사합니다!


편집하다

내 새 데이터 프레임 및 이전 목록 :

abc = ['foo', 'bar']
df2 =
    A    B         C
0  12  NaN      'bla'
1  23  NaN  'bla bla'

다른 데이터 프레임 :

df3 =
    A    B         C                    D
0  12  NaN      'bla'  ['item1', 'item2']
1  23  NaN  'bla bla'        [11, 12, 13]

'abc'목록을 df2.loc[1,'B']및 / 또는에 삽입하고 싶습니다 df3.loc[1,'B'].

데이터 프레임에 정수 값 및 / 또는 NaN 값 및 / 또는 목록 값만있는 열이있는 경우 셀에 목록을 삽입하면 완벽하게 작동합니다. 데이터 프레임에 문자열 값 및 / 또는 NaN 값 및 / 또는 목록 값만있는 열이있는 경우 목록을 셀에 삽입하면 완벽하게 작동합니다. 그러나 데이터 프레임에 정수 및 문자열 값이있는 열과 다른 열이있는 경우 다음을 사용하면 오류 메시지가 나타납니다. df2.loc[1,'B'] = abc또는 df3.loc[1,'B'] = abc.

다른 데이터 프레임 :

df4 =
          A     B
0      'bla'  NaN
1  'bla bla'  NaN

이 삽입물은 완벽하게 작동합니다 : df.loc[1,'B'] = abc또는 df4.loc[1,'B'] = abc.


이후 set_value되었습니다 되지 않는 버전 0.21.0 때문에, 당신은 지금 사용해야합니다 at. ValueErroras 를 올리지 않고 목록을 셀에 삽입 할 수 있습니다 loc. at 항상 단일 값 loc을 참조하고 행과 열뿐만 아니라 값을 참조 할 수 있기 때문이라고 생각합니다 .

df = pd.DataFrame(data={'A': [1, 2, 3], 'B': ['x', 'y', 'z']})

df.at[1, 'B'] = ['m', 'n']

df =
    A   B
0   1   x
1   2   [m, n]
2   3   z

df3.set_value(1, 'B', abc)모든 데이터 프레임에서 작동합니다. 'B'열의 데이터 유형을 관리하십시오. 예 : 목록을 부동 열에 삽입 할 수 없습니다 df['B'] = df['B'].astype(object). 이 경우 도움이 될 수 있습니다.


v0.23 + set_value는 더 이상 사용되지 않습니다.
이제 DataFrame.at레이블 DataFrame.iat로 설정하고 정수 위치로 설정하는 데 사용할 수 있습니다 .


at/로 셀 값 설정iat

# Setup
df = pd.DataFrame({'A': [12, 23], 'B': [['a', 'b'], ['c', 'd']]})
df

    A       B
0  12  [a, b]
1  23  [c, d]

df.dtypes

A     int64
B    object
dtype: object

"B"의 두 번째 행에있는 값을 새 목록에 설정하려면 DataFrane.at다음을 사용하십시오 .

df.at[1, 'B'] = ['m', 'n']
df

    A       B
0  12  [a, b]
1  23  [m, n]

You can also set by integer position using DataFrame.iat

df.iat[1, df.columns.get_loc('B')] = ['m', 'n']
df

    A       B
0  12  [a, b]
1  23  [m, n]

What if I get ValueError: setting an array element with a sequence?

I'll try to reproduce this with:

df

    A   B
0  12 NaN
1  23 NaN

df.dtypes

A      int64
B    float64
dtype: object

df.at[1, 'B'] = ['m', 'n']
# ValueError: setting an array element with a sequence.

This is because of a your object is of float64 dtype, whereas lists are objects, so there's a mismatch there. What you would have to do in this situation is to convert the column to object first.

df['B'] = df['B'].astype(object)
df.dtypes

A     int64
B    object
dtype: object

Then, it works:

df.at[1, 'B'] = ['m', 'n']
df

    A       B
0  12     NaN
1  23  [m, n]

Possible, But Hacky

Even more wacky, I've found you can hack through DataFrame.loc to achieve something similar if you pass nested lists.

df.loc[1, 'B'] = [['m'], ['n'], ['o'], ['p']]
df

    A             B
0  12        [a, b]
1  23  [m, n, o, p]

You can read more about why this works here.


As mentionned in this post pandas: how to store a list in a dataframe?; the dtypes in the dataframe may influence the results, as well as calling a dataframe or not to be assigned to.


Quick work around

Simply enclose the list within a new list, as done for col2 in the data frame below. The reason it works is that python takes the outer list (of lists) and converts it into a column as if it were containing normal scalar items, which is lists in our case and not normal scalars.

mydict={'col1':[1,2,3],'col2':[[1, 4], [2, 5], [3, 6]]}
data=pd.DataFrame(mydict)
data


   col1     col2
0   1       [1, 4]
1   2       [2, 5]
2   3       [3, 6]

참고URL : https://stackoverflow.com/questions/26483254/python-pandas-insert-list-into-a-cell

반응형